All about "Static" variable in JAVA

                        Static KeyWord


In Java, static is keyword that can be applied to variables and methods but not to classes. static is used as an access modifier.
In Java, to call an instance variable or method, an object is required. But a static variable and method can be called without the help of an object. This is the basic difference between static and non-static in Java.


Static with Variable:
If variables are declared as static then only one copy of those variable's exsist for all the objects instansiated.

Java permits to call a static variable or method in three ways.
  1. Can be called without the help of an object.
  2. Can be called with the help of an object.
  3. Can be called with class name.
What is Class Variable? (of Java static Variable Method)
A static variable is also known as "class variable" as all the objects of the whole class refer (or share) the same variable (location); that is, one variable is used by all the objects (in encapsulation, each object will have separate location of a variable). As all the objects refer the same location (variable), no encapsulation exist with static variable.

Static with Method:

The same style of static variables is followed with static methods also and can be called in three ways.

Why the main() is static? (of Java static Variable Method)
main() method is declared as static to allow the JVM to call the main() without the help of an object. JVM is a separate process and to call the method of another process (your program), it requires an object. As the execution starts from the main(), the JVM cannot create an object without entering the main() method. If the main() method is allowed to call without the need of an object, the JVM can create hundreds of objects once enters the main(). For this reason, main() is declared as static.

Restrictions for static method:

There are two main restrictions for the static method. They are:
  • The static method can not use non static data member or call non-static method directly.
  • this and super cannot be used in static context.










---------------------------------------------------------------



Can a local variable be declared static? (of Java static Variable Method)

A local variable cannot be static. If static the meaning of static is lost. A static variable scope is for the objects of whole class and if declared local as static, the purpose of static is lost and compiler raises error.



Comments

Popular posts from this blog

FC Barcelona vs Real Madrid -El Clasico Rivalry.

1NF,2NF, 3NF Normalization

Memory Management (Contiguous and Non-Contiguous ).