Java ยท Chapter 18 of 42
Java Methods
A method is a reusable block of code that performs a task. Methods have a name, a return type (or void), parameters, and a body. Calling a method executes its code and optionally returns a value.
Organizing code into methods reduces duplication and makes programs easier to read, test, and maintain.
Syntax
returnType methodName(parameters) {
// body
return value;
}Declaring methods
A method signature includes access modifier, return type, name, and parameter list, e.g. `public static int add(int a, int b)`.
Calling methods
Call a method by its name followed by arguments in parentheses. The return value can be stored in a variable or used directly.
Example 1 (java)
public class Main {
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = add(3, 4);
System.out.println(result);
}
}Output
7add() takes two ints, returns their sum, which is printed from main.
Key points
- Methods group reusable code under a name.
- void methods return nothing.
- Parameters let you pass data into a method.
- return sends a value back to the caller.
๐ก Note: Keep methods short and focused on a single task for better readability and testing.
