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
}
Example:
class Demo {
void display() {
System.out.println("Hello World");
}
}
Types of Methods in Java:
1. Predefined Methods:
These are already available in Java.
Example:
Math.sqrt(25);
System.out.println("Hello");
2. User-defined Methods:
Methods created by the programmer.
Example:
class Demo {
void greet() {
System.out.println("Welcome!");
}
}
Top comments (0)