Methods Basics
A method in Java is a block of code designed to perform a specific task. Methods promote code reuse, modularity, readability, and maintainability, and they are a fundamental building block of any Java application. This topic is essential for interviews and for understanding OOP, execution flow, and program structure.
What Is a Method?
- A named block of code
- Executes when it is called (invoked)
- May accept parameters
- May return a value
int add(int a, int b) {
return a + b;
}
Why Methods Are Important
- Avoid code duplication
- Improve readability
- Simplify debugging and testing
- Support modular and OOP design
Basic Syntax of a Method
accessModifier returnType methodName(parameterList) {
// method body
}
Breakdown of Method Components
1. Access Modifier
Defines visibility.
- public
- protected
- default (no keyword)
- private
public int add(int a, int b)
2. Return Type
- Specifies the type of value returned
- Use void if no value is returned
void display() { }
3. Method Name
- Should be a verb
- Follows camelCase
calculateTotal()
4. Parameters (Optional)
- Input values to the method
- Defined with type and variable name
int add(int a, int b)
5. Method Body
- Contains executable statements
- Enclosed in {}
Example: Simple Method
public class Calculator {
int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
Calculator c = new Calculator();
int result = c.add(10, 20);
System.out.println(result);
}
}
Method Invocation (Calling a Method)
1. Calling Non-Static Method
Calculator c = new Calculator();
c.add(10, 20);
2. Calling Static Method
Math.max(10, 20);
Types of Methods in Java (Basics)
1. Predefined Methods
- Provided by Java API
- Example: println(), length(), max()
2. User-Defined Methods
- Written by programmers
- Customized logic
Methods Based on Return & Parameters
1. No Return, No Parameters
void greet() {
System.out.println("Hello");
}
2. Return Value, No Parameters
int getNumber() {
return 10;
}
3. No Return, With Parameters
void printSum(int a, int b) {
System.out.println(a + b);
}
4. Return Value, With Parameters
int multiply(int a, int b) {
return a * b;
}
return Statement
- Sends value back to caller
- Terminates method execution
return value;
return; // for void methods
Method Execution Flow
- Method is called
- Control transfers to method
- Parameters are initialized
- Method body executes
- Return value (if any) is sent back
- Control returns to caller
Method Overloading (Preview)
- Same method name
- Different parameter list
- Compile-time polymorphism
int add(int a, int b) { }
int add(int a, int b, int c) { }
Common Beginner Mistakes
- Forgetting return statement
- Mismatch between return type and returned value
- Incorrect method signature
- Confusing static and non-static methods
- Writing large methods instead of modular ones
Interview-Ready Answers
Short Answer
A method is a block of code that performs a specific task and is executed when called.
Detailed Answer
In Java, a method consists of an access modifier, return type, method name, parameters, and body. Methods enable code reuse, modular design, and better maintainability by encapsulating logic into reusable units.
Java Method Examples (Quick Reference)
1. Simple Method Without Parameters
class Demo {
static void greet() {
System.out.println("Hello Java");
}
public static void main(String[] args) {
greet();
}
}
Explanation
- No parameters
- No return value
Output: Hello Java
2. Method With Parameters
class Demo {
static void greet(String name) {
System.out.println("Hello " + name);
}
public static void main(String[] args) {
greet("Selenium");
}
}
Explanation
- name is a parameter
Output: Hello Selenium
3. Method With Return Value
class Demo {
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int sum = add(10, 20);
System.out.println(sum);
}
}
Explanation
- Uses return
Output: 30
4. Ignoring a Return Value
class Demo {
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
add(10, 20);
}
}
Explanation
- Return value ignored
- No output
5. Method Returning String
class Demo {
static String getTool() {
return "Selenium";
}
public static void main(String[] args) {
System.out.println(getTool());
}
}
Explanation
- Methods can return objects
Output: Selenium
6. Multiple Return Statements
class Demo {
static String check(int age) {
if (age >= 18) {
return "Eligible";
}
return "Not Eligible";
}
public static void main(String[] args) {
System.out.println(check(16));
}
}
Explanation
- Only one return executes
Output: Not Eligible
7. Method Calling Another Method
class Demo {
static void start() {
System.out.println("Start");
}
static void process() {
start();
System.out.println("Process");
}
public static void main(String[] args) {
process();
}
}
Explanation
- Method-to-method call
Output:
Start
Process
8. Method Overloading (Different Parameters)
class Demo {
static int add(int a, int b) {
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
System.out.println(add(2, 3));
System.out.println(add(2, 3, 4));
}
}
Explanation
- Same name, different parameter list
Output:
5
9
9. Method Overloading (Different Data Types)
class Demo {
static void show(int a) {
System.out.println("int");
}
static void show(double a) {
System.out.println("double");
}
public static void main(String[] args) {
show(10);
show(10.5);
}
}
Explanation
- Compile-time resolution
Output:
int
double
10. Automatic Type Promotion
class Demo {
static void show(double a) {
System.out.println("double");
}
public static void main(String[] args) {
show(10);
}
}
Explanation
- int promoted to double
Output: double
11. Local Variable Inside Method
class Demo {
static void test() {
int x = 10;
System.out.println(x);
}
public static void main(String[] args) {
test();
}
}
Explanation
- Local scope
Output: 10
12. Local Variable Scope Error
class Demo {
static void test() {
int x = 10;
}
public static void main(String[] args) {
// System.out.println(x); // Compile-time error
}
}
Explanation
- Local variables are not accessible outside method
13. Call by Value (Primitive)
class Demo {
static void change(int x) {
x = 100;
}
public static void main(String[] args) {
int a = 10;
change(a);
System.out.println(a);
}
}
Explanation
- Only value copy is passed
Output: 10
14. Call by Value (Object Reference)
class Demo {
static void change(StringBuilder sb) {
sb.append(" Java");
}
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
change(sb);
System.out.println(sb);
}
}
Explanation
- Object is mutable
Output: Hello Java
15. Reassigning Reference Inside Method
class Demo {
static void change(StringBuilder sb) {
sb = new StringBuilder("New");
}
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Old");
change(sb);
System.out.println(sb);
}
}
Explanation
- Reference reassignment is local
Output: Old
16. Recursive Method
class Demo {
static void count(int n) {
if (n == 0) return;
System.out.println(n);
count(n - 1);
}
public static void main(String[] args) {
count(3);
}
}
Explanation
- Base condition required
Output:
3
2
1
17. Method Execution Order (Stack Behavior)
class Demo {
static void a() {
System.out.println("A");
}
static void b() {
a();
System.out.println("B");
}
public static void main(String[] args) {
b();
System.out.println("Main");
}
}
Explanation
- LIFO execution
Output:
A
B
Main
18. Static vs Non-Static Methods
class Demo {
void nonStatic() {
System.out.println("Non-static");
}
static void staticMethod() {
System.out.println("Static");
}
public static void main(String[] args) {
staticMethod();
Demo d = new Demo();
d.nonStatic();
}
}
Explanation
- Static → class-level
- Non-static → object-level
Output:
Static
Non-static
19. Varargs Method
class Demo {
static void sum(int... nums) {
int total = 0;
for (int n : nums) {
total += n;
}
System.out.println(total);
}
public static void main(String[] args) {
sum(1, 2, 3);
sum(5, 10);
}
}
Explanation
- Variable arguments
Output:
6
15
20. Interview Summary Example (Methods)
class Demo {
static int calc(int x) {
x = x + 10;
return x;
}
public static void main(String[] args) {
int a = 5;
int b = calc(a);
System.out.println(a);
System.out.println(b);
}
}
Explanation
- Call by value
Output:
5
15
Key Takeaway
Methods are the foundation of structured programming in Java. Writing small, clear, and reusable methods is essential for clean code and strong OOP design.