Skip to main content

Java Methods

Methods in Java are blocks of code used to perform specific tasks. They help make your code reusable, organized, and modular.


🧠 Definition​

A method in Java is a group of statements that perform an operation. Methods allow you to reuse code without rewriting it every time.


✨ Fun Fact​

The main() method is just another method in Java, but it’s special because it’s where your program starts running.


πŸ› οΈ Syntax of a Method​

returnType methodName(parameter1, parameter2, ...) {
// method body
}

Example

public int add(int a, int b) {
return a + b;
}

πŸš€ Calling a Method​

To use a method, you "call" it:

int result = add(5, 3);
System.out.println(result); // 8

πŸ”„ Types of Methods​

Predefined Methods – Built-in Java methods (e.g., System.out.println())

User-defined Methods – Created by the programmer

🧱 Static vs Non-static Methods​

Feature Static Method Non-static Method Belongs to Class Object (instance) Call method using Class name Object name Example main(), Math.sqrt() student.getName()

βž• Method Overloading​

Same method name, different parameters:

public int multiply(int a, int b) {
return a * b;
}


public double multiply(double a, double b) {
return a * b;
}

🌍 Real-World Analogy​

Think of a method like a vending machine:

The machine (method) takes input (coins)

It performs a task (select item)

It gives an output (your snack)

Each machine does something specific β€” like a method.

πŸ§’ Explain Like I’m Five (ELI5)​

A method is like a magic spell:

You say its name and give it something

It does the job and gives you the result

You don’t need to know how β€” just what it does

πŸ’» Code Example​

public class Example {

public static void greet() {
System.out.println("Hello!");
}

public static int square(int x) {
return x * x;
}

public static void main(String[] args) {
greet(); // Hello!
int result = square(5);
System.out.println(result); // 25
}
}

πŸ§ͺ Exercises​

Create a method isEven(int number) that returns true if the number is even.

Create a method areaOfRectangle(int length, int width) to return the area.

Overload a method greet() to:

print "Hello!"

accept a name and print "Hello, name!"

⚑ Quick Recap​

A method is a block of code that performs a task.

Methods help make code reusable.

Java supports static and non-static methods.

You can overload methods by changing their parameters.

Next: Java Scope and Lifetime of Variables