Determine Output:
class MyClass{
static final int a = 20;
static final void call(){
System.out.println("two");
}
static{
System.out.println("one");
}
}
public class Test{
public static void main(String args[]){
System.out.println(MyClass.a);
}
}
class MyClass{
static final int a = 20;
static final void call(){
System.out.println("two");
}
static{
System.out.println("one");
}
}
public class Test{
public static void main(String args[]){
System.out.println(MyClass.a);
}
}
A. one
B. one two
C. one two 20
D. 20
E. one 20
Answer: Option E
Join The Discussion
Comments ( 7 )
Related Questions on Declaration and Access Control
What is the default access modifier for class members in Java if no access modifier is specified?
A. public
B. protected
C. private
D. package-private
A. private
B. public
C. protected
D. package-private
What keyword is used to declare a constant in Java, which is implicitly final and static?
A. final
B. const
C. static
D. constant
A. protected
B. private
C. public
D. default
How
Static block executes before the main method, then the control is given to main method so the output is one 20
The answer should be 20. Java will first look for a static block inside the class containing the main method. In this question, unless we create an instance of class MyClass (i.e. using new MyClass() inside the main method), the static block of MyClass will not be called. So the answer should be just 20.
Static block will be executed first. So, it prints "one". Then the main method calls the static varibale (a). As, it is static varibale it can be called by class name. So 20 gets printed. So, the answer is "one 20"
why the static method wasn't called over here?
Option-E
In Java Every time Static block always executed first.That-why first answer is "one" then Execute static variables in Class level.
If only static variable available instead of Static{} block then ans is 20
Answer is wrong of this question, the output should be "one 20" please check this question again carefully. Thank You !!