In Java static keyword is used in many places. The use of static keyword is discussed in this tutorial with some example.
Static Instance Variables
If an instance variable is declared as static, only once the space is allocated in memory, even if multiple instances are created of that class. The static variables are shared by the objects of the class. Moreover, static variables are not allocated at the time of instance creation. The memory for the static variable is allocated at the time of class loading. Thus static variables can be accessed by the class name, instead of object.
When the value of a static variable is updated, the updated value is reflected everywhere.
Static Methods
In the similarway, memory for a static method is also allocated at the time of class loading. Thus static methods can be called without creating an instance of the class. Thus, static methods are accessible by the class name.
A static method can deal with static variables (class level) only.
Static Block
Java supports static block, which is nothing but a code block written in a class (not in method). This block is executed at the time of class loading. As a class is loaded in JVM once, the block is executed once.
Thus, a static block is executed even before calling a static method.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.