Let's talk about the static keyword in Java and what can be asked during the Java interview related to static?
What are the Static Blocks and Static Initializers?
Static blocks are also called as Static Initialization Blocks, a class can have any number of static blocks and they can appear anywhere inside java class. We declare static blocks when we want to initialize static fields in our class. Static blocks gets executed exactly once when the class is loaded. Static blocks are executed even before the constructors are executed.
public class Solution{
public static void main(String[] args){
System.out.println("Main Method");
}
static {
System.out.println("Static block - 1");
}
}
Static block - 1
Main Method
Can We Synchronize Static Methods in Java?
Yes ✅ Synchronized methods are used to protect access to resources that are accessed concurrently. When a resource that is being accessed concurrently belongs to each instance of your class, you use a synchronized instance method; when the resource belongs to all instances (i.e. when it is in a static variable) then you use a synchronized static method to access it.
Can Static Methods Access Instance Variables in Java?
No ❌ Instance variables can’t be accessed in static methods. When we try to access instance variable in static method we get compilation error. The error is as follows:
Cannot make a static reference to the non static field name
How Do We Access Static Members in Java?
Static variables are owned by class rather than by its individual objects. Referring static variables outside the class is by ClassName.myStaticVariable but inside the class it is similar to other instance variables.
Can We Override Static Methods in Java?
No ❌ It is because method overriding is based upon dynamic binding at runtime and static methods are bonded using static binding at compile time.
Can We Define Static Methods Inside Interface?
✅ Since Java8 you can have static methods in an interface (with body). Defining a static method within an interface is identical to defining one in a class. Moreover, a static method can be invoked within other static and default methods.
Can constructors be static in Java?
In general, a static method means that “The Method belongs to the class and not to any particular object” but a constructor is always invoked with respect to an object, so it makes no sense for a constructor to be static.
Top comments (0)