Java Core: Static Flashcards
What is a static variable? When to use them?
A static variable is a field/variable that belongs to an entire class rather than a single object. Memory for this variable is allocated in a stack. The can be used when a class should have a shared variable for all its objects.
What is a static method? When to use them?
A static method is a method that belongs to an entire class rather than a single object of this class. These methods can be used when a class should have a method that exists independently of any object.
What are the static initialization blocks? When to use them?
Code inside static initialization blocks is executed only once - when the class (but not its objects) is first loaded. Usually, they can be used when needed to initialize static variables, but determining the values requires some operations.
What are static inner classes? How are they different from non-static inner classes?
Static inner classes are nested classes that have been defined as static. Unlike non-static, we can use static nested classes without initializing an instance of the outer class. It makes them more practical if you wish to use the nested class several times without using the outer class.
Why is the ‘Main’ method always static in Java?
The ‘main’ method is the program’s entry point when no objects have been created yet, It is always static because JVM should be able to call it before any objects have been created.