Java Methods
A method is a named block of code that performs a specific task. Instead of writing the same code multiple times, a method allows that code to be written once and called (used) whenever needed. Methods make programs more organized, reusable, and easier to maintain.
Think of a method like a recipe — write the recipe once, and follow it whenever needed, without rewriting the steps each time.
Why Use Methods?
- Code Reusability: Write once, use many times.
- Modularity: Break a large problem into smaller, manageable pieces.
- Readability: Code is easier to understand when logic is named and grouped.
- Maintainability: Fix a bug in one place instead of many.
Defining a Method
Syntax
accessModifier returnType methodName(parameterList) {
// method body
return value; // if returnType is not void
}- accessModifier: Controls who can call the method (e.g.,
public,private). - returnType: The data type of the value the method returns. Use
voidif it returns nothing. - methodName: The name used to call the method. Should be a meaningful verb in camelCase.
- parameterList: Input values the method receives (optional). Each parameter has a type and a name.
- return: Sends a value back to the caller. Not needed if return type is
void.
Types of Methods
1. void Method – No Return Value
A void method performs a task but does not send back any value.
public class MethodDemo {
static void greet() {
System.out.println("Welcome to Java!");
}
public static void main(String[] args) {
greet(); // calling the method
greet(); // calling it again
}
}Output:
Welcome to Java!
Welcome to Java!2. Method with Return Value
A method can compute a result and return it using the return keyword.
public class ReturnDemo {
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = add(10, 20);
System.out.println("Sum: " + result); // Sum: 30
}
}3. Method with Parameters
Parameters allow data to be passed into a method. Each call can provide different data.
public class GreetUser {
static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
public static void main(String[] args) {
greet("Alice");
greet("Bob");
greet("Charlie");
}
}Output:
Hello, Alice!
Hello, Bob!
Hello, Charlie!Parameters vs Arguments
- Parameter: The variable listed in the method definition. Example:
String name - Argument: The actual value passed when calling the method. Example:
"Alice"
Method Overloading
Java allows multiple methods with the same name but different parameter lists. This is called method overloading. Java determines which method to call based on the number and types of arguments provided.
public class Overloading {
static int multiply(int a, int b) {
return a * b;
}
static double multiply(double a, double b) {
return a * b;
}
static int multiply(int a, int b, int c) {
return a * b * c;
}
public static void main(String[] args) {
System.out.println(multiply(4, 5)); // 20 – calls int version
System.out.println(multiply(2.5, 3.0)); // 7.5 – calls double version
System.out.println(multiply(2, 3, 4)); // 24 – calls 3-parameter version
}
}Passing Values to Methods
Pass by Value (Primitives)
When a primitive value is passed to a method, a copy of the value is passed. Changes made inside the method do not affect the original variable.
static void changeValue(int x) {
x = 100;
System.out.println("Inside method: " + x);
}
public static void main(String[] args) {
int num = 10;
changeValue(num);
System.out.println("Outside method: " + num); // still 10
}Output:
Inside method: 100
Outside method: 10The return Statement
The return statement ends method execution and optionally sends a value back. A method can only return one value, but it can have multiple return statements (for different conditions).
static String classify(int number) {
if (number > 0) {
return "Positive";
} else if (number < 0) {
return "Negative";
} else {
return "Zero";
}
}
public static void main(String[] args) {
System.out.println(classify(10)); // Positive
System.out.println(classify(-5)); // Negative
System.out.println(classify(0)); // Zero
}Static vs Instance Methods
| Feature | Static Method | Instance Method |
|---|---|---|
| Declaration | Uses static keyword | No static keyword |
| Called on | Class name | Object instance |
| Access to object data | Cannot access instance variables | Can access instance variables |
| Example | Math.sqrt() | name.toUpperCase() |
Complete Example – Temperature Converter
public class TempConverter {
static double celsiusToFahrenheit(double celsius) {
return (celsius * 9.0 / 5.0) + 32;
}
static double fahrenheitToCelsius(double fahrenheit) {
return (fahrenheit - 32) * 5.0 / 9.0;
}
public static void main(String[] args) {
double c = 100.0;
double f = 212.0;
System.out.printf("%.1f°C = %.1f°F%n", c, celsiusToFahrenheit(c));
System.out.printf("%.1f°F = %.1f°C%n", f, fahrenheitToCelsius(f));
}
}Output:
100.0°C = 212.0°F
212.0°F = 100.0°CSummary
- A method is a named block of code that performs a specific task.
- Methods can take parameters (inputs) and return values (outputs).
- Use
voidas the return type when a method does not return anything. - Method overloading allows multiple methods with the same name but different parameters.
- Primitive values are passed by value — changes inside the method do not affect the original.
- Static methods belong to the class; instance methods belong to objects.
