Java Methods
Methods in Java are functions that perform a specific task and return a value. They can be either instance methods (declared within a class and belong to an instance of the class) or static methods (declared within a class but belong to the class itself, not to an instance of the class).
Syntax:
[modifiers] [return type] methodName([parameters]) {
// code to be executed
}
Example:
class Calculator {
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
}
Types of Methods in Java:
Static Method
A static method can be called without creating an instance of the class.
class MathOperations {
static int add(int a, int b) {
return a + b;
}
}
Instance Method
An instance method must be called on an instance of the class.
class MathOperations {
int subtract(int a, int b) {
return a - b;
}
}
Abstract Method
An abstract method is a method that has no implementation. It is declared using the abstract keyword and must be overridden in a subclass.
abstract class Shape {
abstract void draw();
}
Final Method
A final method cannot be overridden by subclasses.
class MathOperations {
final int multiply(int a, int b) {
return a * b;
}
}
Constructor Method
A constructor is a special type of method that is called when an instance of a class is created. For example:
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
}
Synchronized Method
A synchronized method is a method that can be accessed by only one thread at a time. For example:
class Counter {
int count = 0;
synchronized void increment() {
count++;
}
}