Java Methods
A method is a named block of code that runs only when you call it. Methods let you write code once and use it many times.
Creating and Calling a Method
A method is written inside a class. Here static means you can call it without creating an object, and void means it gives nothing back:
Example
public class Main {
static void greet() {
System.out.println("Welcome to the class!");
}
public static void main(String[] args) {
greet();
greet();
}
}Welcome to the class! Welcome to the class!
Parameters
Parameters are values you send into a method. They go inside the brackets, each with a type:
Example
public class Main {
static void showStudent(String name, int age) {
System.out.println(name + " is " + age + " years old");
}
public static void main(String[] args) {
showStudent("Ali", 18);
showStudent("Ayesha", 20);
}
}Ali is 18 years old Ayesha is 20 years old
The values you pass when calling ("Ali", 18) are called arguments.
Return Values
Replace void with a type when the method should give a value back. Use return to send it:
Example
public class Main {
static int totalBill(int price, int quantity) {
return price * quantity;
}
static boolean isAdult(int age) {
return age >= 18;
}
public static void main(String[] args) {
int bill = totalBill(120, 5);
System.out.println("Bill: Rs " + bill);
System.out.println(isAdult(16));
}
}Bill: Rs 600 false
| Part | Example | Meaning |
|---|---|---|
| Return type | int | The type of value the method gives back |
| Name | totalBill | Use camelCase, start with a verb |
| Parameters | (int price, int quantity) | Inputs the method needs |
| Body | { return price * quantity; } | The code that runs |
A method should do one clear job. Small methods with good names make a program easy to read and test.
Method Overloading
Two methods can have the same name if their parameters are different. Java picks the right one based on the arguments:
Example
public class Main {
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(4, 6));
System.out.println(add(2.5, 1.25));
}
}10 3.75
Scope
A variable only exists inside the block { } where it was created. This is called its scope.
Example
public class Main {
static void test() {
int x = 5; // x lives only inside test()
System.out.println(x);
}
public static void main(String[] args) {
test();
// System.out.println(x); error: x is not known here
}
}Recursion
A method can call itself. This is called recursion. It needs a stopping point, or it will never end:
Example
static int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
// factorial(5) gives 120Exercise
Exercise
What does the keyword void mean in a method declaration?
