Beginner
Methods: Parameters and Return Values
📂 Phase 2: Control Flow & Data (Days 6–10) · JavaA method is a reusable block of code that performs a specific task. Breaking a program into methods makes it modular, testable, and far easier to read and maintain than one giant block of code.
Basic Method Syntax
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = add(5, 3);
System.out.println(result); // 8
}
Anatomy of a Method
| Part | Example | Meaning |
|---|---|---|
| Access modifier | public | Who can call this method |
| static | static | Belongs to the class, not an instance (covered fully in OOP) |
| Return type | int | The data type the method sends back |
| Method name | add | Used to call the method |
| Parameters | (int a, int b) | Inputs the method accepts |
Void Methods (No Return Value)
public static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
public static void main(String[] args) {
greet("Vishwas"); // prints: Hello, Vishwas!
// No result to store — void methods perform an action, they don't return data
}
Parameters vs Arguments
Parameters are the variables listed in the method definition. Arguments are the actual values passed in when calling the method.
public static int multiply(int x, int y) { // x, y = parameters
return x * y;
}
int result = multiply(4, 5); // 4, 5 = arguments
Pass-by-Value Behavior
Java is strictly pass-by-value — when you pass a primitive (int, double, etc.) into a method, a copy is passed. Changes inside the method do not affect the original variable.
public static void tryToChange(int num) {
num = 100; // only changes the local copy
}
public static void main(String[] args) {
int x = 5;
tryToChange(x);
System.out.println(x); // still 5, NOT 100
}
Interview tip: For objects and arrays, the reference is copied, not the object itself — so modifying an array's contents inside a method DOES affect the original array, even though Java is technically still "pass-by-value" (it's the reference value being copied).