1.

What is the use of “static” keyword in Java?

Answer»
  • The static KEYWORD is a non-access modifier in Java that is useful for memory management.
  • Static property can be shared by all the objects, no SEPARATE copies of static members will be created on object creation.
  • No need to create the instance of the class for accessing static members, we can directly access them by using the class name.
  • The static keyword can be used with the variable, block, method, and nested classes for memory management.
    • Static variable: When a variable is declared with the static keyword, a single copy of the variable will be created and the same variable will be shared across all objects of the class (a class to which the static variable belongs).
    • Static block: A static block helps with the initialization of the static data members. It is a group of statements WITHIN a Java class and gets executed exactly once when the class is first loaded into the JVM(Java Virtual MACHINE).
    • Static method: If the method is declared with the static keyword, then it is considered a static method. The main( ) method is one of the examples of a static method. Static methods are having restrictions such as they can directly call other static methods only, and they can access static data directly.
    • Static class: Only a nested class can be created as a static class. Nested static class doesn’t need a REFERENCE of Outer class(a class in which the nested class is defined). A static class does not have permission to access non-static members of the Outer class.


Discussion

No Comment Found