DEV Community

SILAMBARASAN A
SILAMBARASAN A

Posted on

Understanding Methods in Java

When you write a Java program, you quickly run into a problem — you end up writing the same lines of code over and over. Methods solve this. Think of a method as a named block of code that you write once and can run as many times as you want.

What is a method?

A method is a reusable block of instructions that performs a specific task. Instead of repeating code, you give that code a name and call it whenever you need it.

Types of Methods in Java

Understanding Predefined and User-defined methods using a real Calculator example.

Java methods come in two flavors. Some are already built into Java — you just use them. Others you write yourself to solve your specific problem. Let's understand both using a Calculator program.

1. Predefined Methods

These are methods that Java has already written for you. They live inside Java's built-in libraries. You don't need to define them — just call them directly.

Look at this line inside our Calculator example:

System.out.println(a + b);
Enter fullscreen mode Exit fullscreen mode

println() is a predefined method. Java wrote it. You simply use it to print something to the screen. You never had to define how printing works — Java handles it internally.
More predefined method examples

// Math class predefined methods
int big = Math.max(10, 5);        // → 10
double root = Math.sqrt(25);     // → 5.0
int abs = Math.abs(-7);          // → 7

// String class predefined methods
"hello".toUpperCase();          // → "HELLO"
"Java".length();                 // → 4
Enter fullscreen mode Exit fullscreen mode

2. User-defined Methods

These are methods you write to perform tasks specific to your program. In our example, add(), sub(), multiply(), and div() are all user-defined methods.

The full Calculator example

public class Calculator {

    public static void main(String[] args) {
        Calculator casio = new Calculator();  // create object

        casio.add(10, 5);       // calls user-defined method
        casio.sub(10, 5);       // calls user-defined method
        casio.multiply(10, 5); // calls user-defined method
        casio.div(10, 5);       // calls user-defined method
    }

    // User-defined method: add
    void add(int a, int b) {
        System.out.println(a + b);
    }

    // User-defined method: sub
    void sub(int a, int b) {
        System.out.println(a - b);
    }

    // User-defined method: multiply
    void multiply(int a, int b) {
        System.out.println(a * b);
    }

    // User-defined method: div
    void div(int a, int b) {
        System.out.println(a / b);
    }
}
Enter fullscreen mode Exit fullscreen mode

OUTPUT :

15
5
50
2
Enter fullscreen mode Exit fullscreen mode

Top comments (0)