A method is a reusable block of organized statements designed to execute a specific task, manipulate object state, and return a computed result. Methods promote the DRY (Don't Repeat Yourself) principle and enhance software modularity.
// Method Syntax:
// [access_modifier] [static] return_type methodName(parameter_list) { ... }
public static int calculateSum(int num1, int num2) {
int total = num1 + num2;
return total; // Must match declared return_type
}
A frequent topic of confusion in technical interviews and BCA exams is whether Java passes arguments by value or reference. Java is 100% Pass-By-Value in all circumstances:
public class PassByValueDemo {
public static void modifyPrimitive(int x) {
x = 999; // Modifies local copy only!
}
public static void modifyArray(int[] arr) {
arr[0] = 500; // Modifies shared Heap array object!
}
public static void main(String[] args) {
int a = 10;
modifyPrimitive(a);
System.out.println("a after method: " + a); // Still 10!
int[] scores = { 10, 20, 30 };
modifyArray(scores);
System.out.println("scores[0] after: " + scores[0]); // Changed to 500!
}
}
Method Overloading occurs when multiple methods in the same class share the exact same method name, but possess different parameter lists:
add(int, int) vs add(int, int, int)print(int) vs print(String)display(int, String) vs display(String, int)public class Calculator {
// 1. Two integer parameters
public int add(int a, int b) {
return a + b;
}
// 2. Overloaded: Three integer parameters
public int add(int a, int b, int c) {
return a + b + c;
}
// 3. Overloaded: Two double parameters
public double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(10, 20)); // Invokes #1 -> 30
System.out.println(calc.add(10, 20, 30)); // Invokes #2 -> 60
System.out.println(calc.add(5.5, 4.5)); // Invokes #3 -> 10.0
}
}
Exam Question: "Can we overload the main method in Java?"
Answer: Yes! You can have multiple overloaded main methods with different parameters (e.g. main(int a), main(String a, String b)). However, the JVM launcher will ONLY invoke the standardized entry point signature public static void main(String[] args). The other overloaded main methods must be called explicitly by your code.
Congratulations on mastering Java fundamentals! Let us enter Section 2 and explore control flow, decision branching, and loops. Proceed to: Java If..Else Conditions →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Method anatomy.
Compile-time vs runtime dispatch.
Constructor overloading.
Methods calling themselves.