static variables in java code example
Example 1: static variables java
Static keyword is used a lot in java.
Static means, you
can access those static variables
without creating an object,
just by using a class name.
This means that only one instance of
that static member is created which
is shared across all instances of the class.
Basically we use static keyword when
all members share same instance.
Example 2: what is static methods and variables
The methods or variables defined as static are shared among all the objects
of the class. The static is the part of the class and not of the object.
The static variables are stored in the class area, and we do not need
to create the object to access such variables.
Therefore, static is used in the case, where we need to define
variables or methods which are common to all the objects of the class.
For example, In the class simulating the collection of the students in
a college, the nameof the college is the common attribute to all the students.
Therefore, the college name will be defined asstatic
Example 3: static data and static methods in java
class JavaExample{
private static String str = "BeginnersBook";
static class MyNestedClass{
public void disp() {
System.out.println(str);
}
}
public static void main(String args[])
{
JavaExample.MyNestedClass obj = new JavaExample.MyNestedClass();
obj.disp();
}
}