Java Methods

What Are Methods in Java?

A method in Java is a block of code designed to perform a specific task. Methods help organize code, make it reusable, and improve readability. Instead of writing the same code multiple times, you can define it once as a method and reuse it whenever needed.

Key Features of Java Methods

  1. Reusability:
    • Code can be reused multiple times by simply calling the method.
  2. Modularity:
    • Methods divide a program into smaller, manageable parts.
  3. Improved Readability:
    • Descriptive method names and well-defined logic enhance code readability.
  4. Parameters:
    • Methods can accept inputs (parameters) and perform operations based on them.
  5. Return Values:
    • Methods can return results after completing their operations.

Syntax of a Method

accessModifier returnType methodName(parameters) {
// Method body (logic or operations)
}

Explanation:

  1. Access Modifier: Controls the visibility of the method (e.g., public, private).
  2. Return Type: Specifies the type of value the method will return (e.g., int, String, void).
  3. Method Name: Represents the name of the method (should be descriptive).
  4. Parameters: Inputs passed to the method (optional).
  5. Method Body: Contains the logic or operations performed by the method.

Types of Methods in Java

  1. Predefined Methods:
    • These are built-in methods provided by Java, such as Math.sqrt() or System.out.println().
  2. User-Defined Methods:
    • These are methods created by the programmer to perform specific tasks.

Creating and Using Methods

Defining a Method

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

Calling a Method

public static void main(String[] args) {
MyClass obj = new MyClass(); // Create an object of the class
int result = obj.addNumbers(5, 10); // Call the method
System.out.println("Sum: " + result);
}

Output:

Sum: 15

Void vs. Return Methods

Void Method

A void method does not return any value. It performs an action but does not provide a result.

public void displayMessage() {
System.out.println("Hello, World!");
}

Calling the Method:

obj.displayMessage(); // Output: Hello, World!

Method with Return Type

A method with a return type provides a result when it is executed.

public int square(int number) {
return number * number;
}

Calling the Method:

int result = obj.square(5); // result = 25

Parameters in Methods

Parameterized Method

A method can accept parameters to perform operations based on input values.

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

Calling the Method:

obj.greet("Alice"); // Output: Hello, Alice!

Method Without Parameters

A method without parameters performs the same task regardless of inputs.

public void showMessage() {
System.out.println("Welcome to Java Programming!");
}

Calling the Method:

obj.showMessage();

Method Overloading

Java allows multiple methods with the same name but different parameters. This is called method overloading. It helps improve code flexibility.

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

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

Calling the Methods:

System.out.println(obj.multiply(5, 10));   // Output: 50
System.out.println(obj.multiply(2.5, 3.0)); // Output: 7.5

Static Methods

A static method belongs to the class rather than any specific object. It can be called without creating an object.

public static void displayInfo() {
System.out.println("Static methods belong to the class.");
}

Calling the Method:

MyClass.displayInfo();

Common Java Built-In Methods

  1. Math.sqrt(): Calculates the square root of a number.
  2. System.out.println(): Prints a message to the console.
  3. Arrays.sort(): Sorts an array.

Real-World Example

public class BankAccount {
private double balance;

// Method to deposit money
public void deposit(double amount) {
balance += amount;
System.out.println("Deposited: " + amount);
}

// Method to withdraw money
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Insufficient balance!");
}
}

// Method to check balance
public double checkBalance() {
return balance;
}
}

Using the Class:

BankAccount account = new BankAccount();
account.deposit(1000);
account.withdraw(500);
System.out.println("Current Balance: " + account.checkBalance());

Output:

Deposited: 1000  
Withdrawn: 500
Current Balance: 500

Leave a Comment