Q1. Can static method access instance variables ?
Ans. Though Static methods cannot access the instance variables directly, They can access them using instance handler.
Q2. Does java allow overriding static methods ?
Ans. No. Static methods belong to the class and not the objects. They belong to the class and hence doesn't fit properly for the polymorphic behavior.
Q3. When are static variables loaded in memory ?
Ans. They are loaded at runtime when the respective Class is loaded.
Q4. Can we serialize static variables ?
Ans. No. Only Object and its members are serialized. Static variables are shared variables and doesn't correspond to a specific object.
Q5. Explain static blocks in Java ?
Ans. A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:
static {
// whatever code is needed for initialization goes here
}
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
Q6. Can we override static methods ? Why ?
Ans. No.
Static methods belong to the class and not the objects. They belong to the class and hence doesn't fit properly for the polymorphic behavior.
A static method is not associated with any instance of a class so the concept of overriding for runtime polymorphism using static methods is not applicable.
Q7. Can we access instance variables within static methods ?
Ans. Yes.
we cannot access them directly but we can access them using object reference.
Static methods belong to a class and not objects whereas non static members are tied to an instance. Accessing instance variables without the instance handler would mean an ambiguity regarding which instance the method is referring to and hence its prohibited.
Q8. What will happen if we remove the static keyword from main method ?
Ans. Program will compile but will give a "NoSuchMethodError" during runtime.
Q9. Which memory areas does instance and static variables use ?
Ans. instance variables are stored on stack whereas static variables are stored on heap.
Q10. How can we run a java program without making any object?
Ans. By putting code within either static method or static block.
Q11. How can we create objects if we make the constructor private ?
Ans. We can do so through a static public member method or static block.
Q12. What is a nested interface ?
Ans. Any interface declared inside a class or an interface. It is static by default.