Java Methods
A method in Java is a reusable block of code that performs a specific task
and executes only when invoked. Methods help organize programs into logical
units, improve readability, and promote code reuse.
In Java, methods are also commonly referred to as functions.
What Is a Method in Java?
A method:
- Belongs to a class
- Contains executable statements
- Can accept input (parameters)
- May return a value
- Runs only when called
Using methods prevents repetition by allowing you to define once and
use many times.
Why Use Methods?
Methods provide several advantages:
- Code reusability
- Better program structure
- Easier debugging
- Improved readability
- Reduced duplication
Declaring (Creating) a Method
A method must be declared inside a class. The basic syntax
is:
modifier returnType methodName() {
// method body
}
Example 1: Creating a Simple Method
public class MethodCreationExample {
static void displayMessage() {
System.out.println("Welcome to Java
programming!");
}
}
Explanation
- display Message → method name
- static → belongs to the class (no object needed)
- void → no return value
- Method body → statements executed when called
Calling a Method
To execute a method, write its name followed by parentheses
().
Example 2: Calling a Method from main
public class MethodCallExample {
static void greetUser() {
System.out.println("Hello,
user!");
}
public static void main(String[] args) {
greetUser();
}
}
Output
Hello, user!
Calling a Method Multiple Times
Methods can be reused anywhere within the same class.
Example 3: Reusing a Method
public class MethodReuseExample {
static void printDivider() {
System.out.println("-----------");
}
public static void main(String[] args) {
printDivider();
System.out.println("Section
1");
printDivider();
System.out.println("Section
2");
printDivider();
}
}
Output
-----------
Section 1
-----------
Section 2
-----------
Understanding static and void
static
- Indicates the method belongs to the class rather than an object
- Can be called directly from main
- Common in utility/helper methods
void
- Specifies the method returns no value
- Used when the method performs an action only
Built-in vs User-Defined Methods
Java provides many built-in methods, such as:
System.out.println("Text");
Math.max(5, 10);
You can also create custom methods for your program’s
needs.