Java Methods
Building blocks of Java programs
🔧 What are Java Methods?
Java methods are reusable blocks of code that perform specific tasks. They help organize code, avoid repetition, and make programs more readable and maintainable.
// This is a simple Java method example
public static void sayHello() {
System.out.println("Hello, World!");
}
Output:
Hello, World!
Key Method Concepts
Declaration
Define method name and structure
public static void methodName() {}
Calling
Execute the method by calling it
methodName();
Reusability
Use the same method multiple times
methodName();
methodName();
Purpose
Each method has a specific task
calculateSum();
printResult();
🔹 Method Structure
Every Java method has a specific structure:
// Method structure explained
public static void greetUser() {
System.out.println("Welcome to Java!");
System.out.println("Let's learn methods!");
}
// Calling the method
public static void main(String[] args) {
greetUser(); // This calls our method
}
Output:
Welcome to Java!
Let's learn methods!
🔹 Method Keywords Explained
Understanding method keywords:
// public - can be accessed from anywhere
// static - belongs to the class, not an instance
// void - doesn't return any value
public static void displayMessage() {
System.out.println("This is a public static void method");
}
// Another example
public static void showNumbers() {
System.out.println("Number 1: " + 1);
System.out.println("Number 2: " + 2);
}
Output:
This is a public static void method
Number 1: 1
Number 2: 2
🔹 Multiple Methods Example
Creating and using multiple methods:
public class MethodExample {
// Method 1: Display welcome message
public static void welcome() {
System.out.println("=== Welcome to Java ===");
}
// Method 2: Display goodbye message
public static void goodbye() {
System.out.println("=== Goodbye! ===");
}
// Main method calls other methods
public static void main(String[] args) {
welcome();
System.out.println("Learning Java methods is fun!");
goodbye();
}
}
Output:
=== Welcome to Java ===
Learning Java methods is fun!
=== Goodbye! ===