DEV Community

Divya Divya
Divya Divya

Posted on

Methods in Java?

Method:
A method in Java is a block of code that performs a specific task and runs only when it is called.

Predefined Methods (Built-in Methods)

Methods that are already available in Java libraries. You don’t create them — you just use them.

Example:

class Test {
    public static void main(String[] args)
 {
        double result = Math.sqrt(16);  // predefined method
        System.out.println(result);
    }
}
Enter fullscreen mode Exit fullscreen mode

Execution Flow:

  • Program starts from main()
  • Math.sqrt(16) is called
  • Control goes to Java’s built-in Math class
  • Square root is calculated → 4.0
  • Value 4.0 is returned to main()
  • System.out.println(result) prints 4.0

Key Points

  • Provided by Java API
  • Saves development time
  • Already tested and optimized

User-defined Methods

Methods that are created by the programmer to perform a specific task.

Example:

class Test {

    int square(int n) {   // user-defined method
        return n * n;
    }

    public static void main(String[] args) {
        Test obj = new Test();
        int result = obj.square(4);
        System.out.println(result);
    }
}
Enter fullscreen mode Exit fullscreen mode

Execution Flow

  • Program starts from main()
  • Object obj is created
  • obj.square(4) is called
  • Control moves to square() method
  • Inside method: n * n = 16
  • Value 16 is returned to main()
  • System.out.println(result) prints 16

Key Points:

  • Written by developer
  • Custom logic
  • Improves code reuse and readability

Both Methods

class Test {

    int square(int n) {
        return n * n;
    }

    public static void main(String[] args) {
        Test obj = new Test();

        int res1 = obj.square(5);        // user-defined
        double res2 = Math.sqrt(res1);  // predefined

        System.out.println(res2);
    }
}
Enter fullscreen mode Exit fullscreen mode

Execution Flow (Step-by-step)

  • obj.square(5)

→ Calls user-defined method

→ 5 * 5 = 25

→ res1 = 25

  • Math.sqrt(res1)

→ Math.sqrt(25)

→ returns 5.0 (double value)

→ res2 = 5.0

  • System.out.println(res2)

→ prints 5.0

Top comments (0)