In Java, variables, which are declared with the static keyword, belong to the class, not to the instance of the class. This means that we do not need to initialize objects to use variables that are declared with the static keyword in those classes.
For example, we have the following class:
1 2 3 4 5 6 7 8 9 10 |
package com.huongdanjava.javaexample; public class Example { private static final String NAME = "Khanh"; public static void main(String[] args) { System.out.println(Example.NAME); } } |
In the Example class above, I declared NAME to be static. Then, I do not need to initialize the object for the Example class, but I still print out the value of NAME.
Result:
For the same approach, suppose you define a static method in the Example class as follows:
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.huongdanjava.javaexample; public class Example { private static int sum(int a, int b) { return a + b; } public static void main(String[] args) { System.out.println(Example.sum(2, 3)); } } |
As you can see, you do not need to initialize the Example object, but you can also call the sum() static method.
Result:
Static variables can be declared in normal classes, abstract classes, or interface classes.
But for methods from Java 7 and earlier, we can only declare static methods in normal classes or abstract classes. If declared in the interface will be prompted error.
For example:
From Java 8, Java has allowed us to declare static methods in our interface class.
For example:
When you run you will also see the results as above.
priya
The static keyword can be used with the variables, blocks, methods, imports and nested classes. A static variable is common to all objects of the class unlike normal variable.