Java Docs

Java Documentation

Java Methods

A method is a block of code that performs a specific task. Methods help divide complex problems into smaller chunks, making code easier to understand and reusable.

Declaring a Method

Syntax of a Java method:

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

Example: Method to add two numbers:

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

  public static void main(String[] args) {
    Main obj = new Main();
    int sum = obj.addNumbers(25, 15);
    System.out.println("Sum is: " + sum);
  }
}

Output

Output: Sum is: 40

Method Return Type

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

public static void main(String[] args) {
    int result = square(10);
    System.out.println("Squared value of 10 is: " + result);
}

Output

Output: Squared value of 10 is: 100

Method Parameters

class Main {
  public void display1() {
    System.out.println("Method without parameter");
  }

  public void display2(int a) {
    System.out.println("Method with a single parameter: " + a);
  }

  public static void main(String[] args) {
    Main obj = new Main();
    obj.display1();
    obj.display2(24);
  }
}

Output

Output:
Method without parameter
Method with a single parameter: 24

Standard Library Methods

Java provides built-in methods like Math.sqrt() or System.out.print(). You can use them without defining your own method.

public class Main {
  public static void main(String[] args) {
    System.out.print("Square root of 4 is: " + Math.sqrt(4));
  }
}

Output

Output: Square root of 4 is: 2.0

Advantages of Methods

  • Code Reusability: Write once, use multiple times.
  • Better readability and easier debugging.

Example: Using a method for code reusability:

public class Main {
  private static int getSquare(int x){
    return x * x;
  }

  public static void main(String[] args) {
    for (int i = 1; i <= 5; i++) {
      int result = getSquare(i);
      System.out.println("Square of " + i + " is: " + result);
    }
  }
}

Output

Output:
Square of 1 is: 1
Square of 2 is: 4
Square of 3 is: 9
Square of 4 is: 16
Square of 5 is: 25