Why do we use static keywords?
- The static keyword in Java is used for memory management mainly.
- It makes the program more efficient by saving memory.
The static can be:
- Variable (also known as a class variable)
- Method (also known as a class method)
- Block
- Nested class
Understanding the problem without static variable
Suppose there are 500 students in my college, now all instance data members will get memory each time when the object is created. All students have its unique rollno and name, so instance data member is good in such case. Here, "college" refers to the common property of all objects. If we make it static, this field will get the memory only once.
Example of static variable
An object is not required to call a static method. Because static keyword has no relation with the object.
Restrictions of using the static method :
- Static Method can't use non static member.
- "this" and "super" keyword can't be used here.
Static Block
- Is used to initialize the static data member.
- It is executed before the main method at the time of class loading.
Q) Can we execute a program without main() method?
Ans) No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK 1.7, it is not possible to execute a Java class without the main method.
Comments
Post a Comment