Read Also: Java Interview Questions for Senior Java Developers
Interview Questions on static keyword in Java
Q1. What is static in Java?In Java, static is a keyword and non-access modifier. static keyword can be applied to variables, methods, nested classes, and blocks(static block).
Q2. Can we override the static method in Java?
No, we can not override the static method in Java.
Q3. Can we overload the static method in Java?
Yes, we can overload the static method in Java.
Q4. Why main() method is declared as public static in Java?
I have already shared the answer in detail here.
Q5. What is a static block in Java?
A static block is a block of code inside a Java class declared with static keyword and opening and closing curly braces. It is executed when a class is first loaded into the JVM i.e. before the main() method. It is mostly used to initialize the static data members as shown below in the example.
Example:
public class StaticBlockExample {
// static block
static
{
// static data member
int num = 10;
System.out.println(num);
}
public static void main(String args[]) {
System.out.println("Alive is Awesome");
}
}
Output:
10
Alive is Awesome
Q6. Can we have or declare multiple static blocks in our code?
Yes, we can have multiple static blocks in our code. They will be executed in the same order they are written.
Q7. Can we declare constructors as static in Java?
Constructor is always invoked with respect to an object while static belongs to the class level. Hence, constructors can not be declared as static in Java.
Q8. Can we call superclass static method in subclass in Java?
Yes, we can call superclass static method in subclass in Java but we cannot override it.
Q9. Can we access non-static data member in static method in Java?
No, we can only access static data members inside the static method in Java.
Q10. Can we use super or this in static context?
No, we can not use super or this in static context.
Q11. Is the following line valid:
static public void main(String args[])
Yes, the above line is valid since we can change the order of modifiers in the main() method.
That's all for today. Please mention in the comments if you have any questions related to interview questions on static keyword in Java.