🧱 Part 6: Java Methods – Reuse and Organize Your Code
Ever write the same code over and over? What if you could just write it once and use it again whenever you want? That’s what methods (also called functions) are for!
In Java, a method is a named block of code that does something — and you can call it (use it) as many times as you like.
📌 What Is a Method in Java?
A method is like a tool: you build it once, then use it whenever needed. It can take inputs (called parameters
) and give back a result (using return
).
🛠️ A Basic Java Method Example
// Define the method
public static void sayHello() {
System.out.println("Hello, friend!");
}
// Use (call) the method
sayHello(); // prints: Hello, friend!
Let’s break it down:
public static
: Java keywords you’ll use for nowvoid
: This method doesn’t return anythingsayHello()
: The name of the method{ ... }
: The code that runs when you call it
🧮 Methods That Return a Value
Let’s make a method that adds two numbers and returns the result:
public static int addNumbers(int a, int b) {
return a + b;
}
// Use it
int result = addNumbers(3, 5);
System.out.println("Sum: " + result); // Sum: 8
Key parts:
int
before method name → it returns an integerint a, int b
→ input parametersreturn a + b;
→ sends the result back
🧪 Try It Yourself: Make a Greeting Method
public static void greetUser(String name) {
System.out.println("Hi, " + name + "!");
}
// Call it
greetUser("Arthur");
greetUser("Elly");
Output:
Hi, Arthur!
Hi, Elly!
🎯 Why Use Methods?
- ✅ Makes your code cleaner
- ✅ Easier to reuse code
- ✅ Breaks your program into smaller, manageable parts
💡 Method with Multiple Returns
Let’s make a method that checks if a number is even or odd:
public static String checkEven(int num) {
if (num % 2 == 0) {
return "Even";
} else {
return "Odd";
}
}
// Call it
System.out.println(checkEven(7)); // Output: Odd
📌 Java Method Cheat Sheet
// Method without return
public static void greet() {
System.out.println("Hello!");
}
// Method with return
public static int square(int x) {
return x * x;
}
// Call methods
greet();
int squared = square(4); // 16
🔜 Coming Up in Part 7
Next time, we’ll explore:
🧱 Java Classes and Objects — your first step into object-oriented programming
🐾 How to create blueprints (classes) and real things (objects)
🎯 Why OOP is key to writing clean, reusable Java code
🎉 You’ve just mastered methods — that’s a big milestone toward building powerful Java programs!