DEV Community

Adhi sankar
Adhi sankar

Posted on

Methods in Java

A method in Java is a block of code that performs a specific task. Methods help us reuse code, reduce repetition, and make programs easier to understand.

Basic Syntax

returnType methodName(parameters) {
    // code
}
Enter fullscreen mode Exit fullscreen mode

Example

class Main {

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

    public static void main(String[] args) {
        greet();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Hello Java!
Enter fullscreen mode Exit fullscreen mode

Method with Parameters

A method can accept values called parameters.

static int add(int a, int b) {
    return a + b;
}
Enter fullscreen mode Exit fullscreen mode

We can call it like this:

int result = add(10, 20);
System.out.println(result);
Enter fullscreen mode Exit fullscreen mode

Output:

30
Enter fullscreen mode Exit fullscreen mode

Here, a and b are parameters, while 10 and 20 are arguments.

Types of Methods

Methods can be commonly classified as:

  1. No parameter and no return value
  2. Parameter but no return value
  3. No parameter but return value
  4. Parameter and return value

Method Overloading

Java also supports method overloading, where multiple methods have the same name but different parameters.

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

static int add(int a, int b, int c) {
    return a + b + c;
}
Enter fullscreen mode Exit fullscreen mode

Why Use Methods?

  • Code reusability
  • Less code duplication
  • Better readability
  • Easier debugging
  • Breaks a large program into smaller tasks

Conclusion

Methods are one of the most important concepts in Java. By using methods, we can write clean, reusable, and organized code. Understanding parameters, return values, and method overloading is especially important for Java programming and interviews.

Top comments (0)