Java Interview Questions Set 8
Categories: Java 8(JDK1.8)
Can we override the static methods?
No, we can't override static methods.
What is the static block?
Static block is used to initialize the static data member. It is executed before the main method, at the time of classloading.
class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Can we execute a program without main() method?
No, It was possible before JDK 1.7 using the static block. Since JDK 1.7, it is not possible.
What if the static modifier is removed from the signature of the main method?
Program compiles. However, at runtime, It throws an error "NoSuchMethodError."
What is the difference between static (class) method and instance method?
static or class methodinstance method
1)A method that is declared as static is known as the static method. - A method that is not declared as static is known as the instance method.
2)We don't need to create the objects to call the static methods. -The object is required to call the instance methods.
3)Non-static (instance) members cannot be accessed in the static context (static method, static block, and static nested class) directly. - Static and non-static variables both can be accessed in instance methods.
4)For example: public static int cube(int n){ return n*n*n;} - For example: public void msg(){...}.