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