static variables code example
Example 1: can non static method access static variable
Yes, a non-static method can access a static
variable or call a static method in Java.
There is no problem with that because of
static members . both static variable and
static methods belongs to a class and can be
called from anywhere, depending upon
their visibility. For example, if a
static variable is private then it can
only be accessed from the class itself,
but you can access a public static variable
from anywhere by calling with classname.
Example 2: what is static variable
The static variable is used to refer to the common property of all objects
(that is not unique for each object),
e.g., The company name of employees, college name of students, etc.
Static variable gets memory only once in the class area at the time of
class loading. Using a static variable makes your program more
memory efficient (it saves memory). Static variable belongs to the class
rather than the object.