You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Methods let you break code into reusable, named blocks. Arrays let you store multiple values of the same type in a single variable. Together they are foundational building blocks for every Java program.
A method has a return type, a name, and zero or more parameters:
public static int add(int a, int b) {
return a + b;
}
accessModifier static returnType methodName(parameterList) {
// body
}
| Part | Example | Meaning |
|---|---|---|
public | Access modifier | Visible everywhere |
static | Belongs to class | Can be called without creating an object |
int | Return type | The method returns an integer |
add | Method name | How you call the method |
(int a, int b) | Parameters | Input values |
int result = add(3, 7); // result = 10
Methods that do not return a value use void:
public static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
You can define multiple methods with the same name but different parameter lists:
public static int add(int a, int b) {
return a + b;
}
public static double add(double a, double b) {
return a + b;
}
public static int add(int a, int b, int c) {
return a + b + c;
}
The compiler selects the correct method based on the argument types.
Use ... to accept a variable number of arguments:
public static int sum(int... numbers) {
int total = 0;
for (int n : numbers) {
total += n;
}
return total;
}
// Usage:
sum(1, 2); // 3
sum(1, 2, 3, 4, 5); // 15
Tip: Varargs must be the last parameter in the method signature.
An array is a fixed-size, ordered collection of elements of the same type.
// Declare and allocate
int[] numbers = new int[5]; // 5 elements, all initialised to 0
// Declare and initialise with values
int[] scores = {90, 85, 78, 92, 88};
// Access elements (0-indexed)
int first = scores[0]; // 90
int last = scores[4]; // 88
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.