Java Methods
What is a Method?
- A method is a block of code that performs a specific task.
- Methods make code reusable and organized.
Basic Syntax:
returnType methodName(parameters) {
// code to execute
}
Example:
class Calculator {
int add(int a, int b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
int sum = calc.add(5, 3);
System.out.println("Sum: " + sum);
}
}
Output:
Sum: 8
Important Parts of a Method:
Part | Meaning |
---|---|
returnType | What the method returns (e.g., int, void, String) |
methodName | Name of the method |
parameters | Input values (optional) |
body | Code to execute |
Types of Methods:
- Instance Methods → Belong to objects.
- Static Methods → Belong to class (use static keyword).
Example of static method:
class MathOperations {
static int square(int num) {
return num * num;
}
}
public class Main {
public static void main(String[] args) {
int result = MathOperations.square(5);
System.out.println("Square: " + result);
}
}