How does static modifier work?



How does static modifier work?..

Answer / javamasque

Static Variable:
• The variables are class variables.
• These come into existence as class in loaded into JVM.
• The variable remains live as long as class is exists in JVM or garbage collected.
• The variable’s state is common for all instances of the belonging class.
• If any instance of belonging to class modify the value of static variable then the modified value reflects for all.
• Static variables are only accessible in static method only.
• As a good practice, it should be referenced by Class name not by instance.

Static Method:
• The methods are class methods.
• The method is equally defined for all instances the class.
• It is good practice, the static method should be referenced by its class name instead of instance variables.
• This method can only access static variables but not the instance variables.
• Static method will be overloaded but won’t be overridden.
• As there is a common functionality that will be used for a set of other classes in an application, then we have to keep the functionality in static method.
• Mostly factory pattern and singleton pattern use static method.
• Utility classes use static methods

Static Class
• Only a nested class can be static class, top-level class can’t be static.
• A static nested class can only access static members of top-level class.
• A static nested does not require an instance of top-level class to be instantiated.
<<Top-level class name>>.<<Inner static class name>> newClass = new <<Top-level class name>>.<<Inner static class name>>();
• It is completely separate class that has no link with instance of top-level class.

Static block
• Static block is used to initialize static variables of a class.
• Static block is loaded at once at the time of class loading.
• This block may present anywhere in java source but it is executed before constructor at run time.
• If there is multiple static blocks, then it is executed in a sequence as it is found in source file.

Is This Answer Correct ?    4 Yes 0 No

Post New Answer

More Core Java Interview Questions

Same common question what is Map,Set,HashMap,List????

4 Answers   Symphony,


What is immutable in java?

0 Answers  


what is aberivation of java?

14 Answers  


What is foreach loop in java?

0 Answers  


What is an iterator java?

0 Answers  






How to do encapsulation in java?

0 Answers  


what is the difference between pagecontext and servletcontext?

5 Answers   JBA Infotech, TCS,


Explain when classnotfoundexception will be raised ?

0 Answers  


what is use of threads how many ways to create thread

3 Answers   iTrust, Verizon,


how we can create packages in java?

0 Answers  


Explain why wait(), notify() and notifyall() methods are in object class rather than in the reading class?

0 Answers  


How will you serialize a singleton class without violating singleton pattern?

0 Answers  


Categories