DEV Community

S Sarumathi
S Sarumathi

Posted on

Methods In Java

What is a Method in Java?

  • A method in Java is a block of code that performs a specific task. It runs only when it is called (invoked).

    • Think of a method like a mini-program inside your program.

Basic Syntax

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

Example:

class Demo {
    void display() {
        System.out.println("Hello World");
    }
}
Enter fullscreen mode Exit fullscreen mode

Types of Methods in Java:

1. Predefined Methods:
These are already available in Java.

Example:

Math.sqrt(25);
System.out.println("Hello");

Enter fullscreen mode Exit fullscreen mode

2. User-defined Methods:
Methods created by the programmer.

Example:

class Demo {
    void greet() {
        System.out.println("Welcome!");
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)