Defining Methods
Defining Methods in Java
A method encapsulates a reusable block of code. Every method in Java belongs to a class.
Method signature The signature consists of the method name and parameter types (not return type). Signature determines overloading.
Return types
- Declare the return type before the method name.
- Use
voidwhen the method returns nothing. - Every non-void code path must have a
returnstatement.
Parameters Java passes primitives by value and objects by reference to the object (the reference itself is copied). Modifying a primitive parameter does not affect the caller's variable.
static vs instance methods
- static: belongs to the class, called as
ClassName.method(), nothis. - instance: belongs to an object, called as
object.method(), can accessthis.
Key points:
- Method names follow camelCase by convention.
- Keep methods short and focused on a single responsibility.
- Access modifiers (
public,private,protected) control visibility.
Code Examples
public class Calculator {
private double memory = 0;
// Static utility method
public static int add(int a, int b) {
return a + b;
}
// Instance method using this
public void store(double value) {
this.memory = value;
}
public double recall() {
return this.memory;
}
public static void main(String[] args) {
System.out.println(Calculator.add(10, 5));
Calculator calc = new Calculator();
calc.store(42.5);
System.out.println(calc.recall());
}
}Static methods can be called without an instance. Instance methods operate on the object's state via this.
public class StringUtils {
public static boolean isPalindrome(String s) {
String cleaned = s.toLowerCase().replaceAll("[^a-z0-9]", "");
String reversed = new StringBuilder(cleaned).reverse().toString();
return cleaned.equals(reversed);
}
public static void printBanner(String message) {
String border = "=".repeat(message.length() + 4);
System.out.println(border);
System.out.println("| " + message + " |");
System.out.println(border);
}
public static void main(String[] args) {
System.out.println(isPalindrome("racecar"));
System.out.println(isPalindrome("hello"));
printBanner("Java");
}
}void methods produce side effects (like printing) instead of returning a value. Non-void methods must return on every path.
Quick Quiz
1. What does `void` as a return type indicate?
2. How are primitive arguments passed to Java methods?
Was this lesson helpful?