A static method in Java belongs to a class but not to any instance of that class. This means you can invoke a static method on a class rather than an object of that class.
The "static" keyword is used in the method declaration to define a static method.
public class MyClass {
public static void myStaticMethod() {
}
}
Static Method Characteristics
- They can be invoked without first establishing a class instance.
- They can only access static variables and methods or variables and methods that are local to the method, not instance variables or instance methods of the class.
- They can be accessed from other classes without requiring the creation of an instance of the class by using class name followed by the method name, as in MyClass.myStaticMethod().
- They are frequently used for utility methods that execute a generic task without requiring any specific state to be maintained.
- It's worth noting that you may use the same "static" keyword to define static variables in a class.
- All instances of the class share these variables and can be accessed by using the class name followed by the variable name,
MyClass.myStaticVariable.
Example:
public class Calculator {
public static int add(int a, int b) {
return a + b;
}
}
The Calculator class in this example has a static method called add that takes two integer parameters and returns their sum. This method can be reached without generating a Calculator instance.
package week1.day2;
public class Calculator {
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int add = Calculator.add(33, 44);
System.out.println(add);
}
}
- Log in to post comments