java static variable usage code example
Example 1: static in java
The static keyword in Java is used for memory management mainly. We can apply static keyword with
variables, methods, blocks and nested classes. The static keyword belongs to the class
than an instance of the class.
The static can be:
Variable (also known as a class variable)
Method (also known as a class method)
Block
Nested class
Example 2: static data and static methods in java
class JavaExample{
private static String str = "BeginnersBook";
//Static class
static class MyNestedClass{
//non-static method
public void disp() {
/* If you make the str variable of outer class
* non-static then you will get compilation error
* because: a nested static class cannot access non-
* static members of the outer class.
*/
System.out.println(str);
}
}
public static void main(String args[])
{
/* To create instance of nested class we didn't need the outer
* class instance but for a regular nested class you would need
* to create an instance of outer class first
*/
JavaExample.MyNestedClass obj = new JavaExample.MyNestedClass();
obj.disp();
}
}