In this tutorial, we will learn how to use the Java static keyword.
In Java, if we want to access class members, we must first create an instance of the class. But there will be situations where we want to access class members without creating any variables.
In those situations, we can use the static
keyword in Java. If we want to access class members without creating an instance of the class, we need to declare the class members static.
The Math
class in Java has almost all of its members static. So, we can access its members without creating instances of the Math class.
public class Main {
public static void main( String[] args ) {
// accessing the methods of the Math class
System.out.println("Absolute value of -12 = " + Math.abs(-12));
System.out.println("Value of PI = " + Math.PI);
System.out.println("Value of E = " + Math.E);
System.out.println("2^2 = " + Math.pow(2,2));
}
}
Absolute value of -12 = 12
Value of PI = 3.141592653589793
Value of E = 2.718281828459045
2^2 = 4.0
In the above example, we have not created any instances of the Math class. But we are able to access its methods: abs()
and pow()
and variables: PI
and E
.
It is possible because the methods and variables of the Math class are static.