Methods in Java

๐Ÿ”ท What is a Method?

A method in Java is a block of code that performs a specific task. It helps to organize code, promote reusability, and make it more readable.


๐Ÿ”ธ Benefits of Methods:

  • โœ… Avoid code duplication

  • โœ… Break complex tasks into smaller units

  • โœ… Makes code modular and easier to maintain


โœ… Syntax:

returnType methodName(parameters) {
// method body
}

๐Ÿ”น Example:

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

๐Ÿ”ธ Types of Methods in Java:

  1. Predefined Methods โ€“ Provided by Java (e.g., System.out.println())

  2. User-defined Methods โ€“ Created by the programmer


๐Ÿ”„ Method with Parameters and Return:

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

๐Ÿงช Usage:

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

๐Ÿ”„ Calling a Method:

To call a method, use:

objectName.methodName(arguments);

๐Ÿ” Method Overloading:

You can define multiple methods with the same name but different parameters:

void display() {
System.out.println("No parameters");
}
void display(String name) {
System.out.println(“Hello “ + name);
}


๐Ÿ“Œ Key Points:

  • A method must be called to execute.

  • The main() method is the entry point for every Java program.

  • Method names should follow camelCase.

Related Posts