Declaration And Access Control - Study Mode

[#46] What will be the output? public class Test{
static{
int a = 5
}
public static void main(String args[]){
new Test().call()
}
void call(){
this.a++
System.out.print(this.a)
}
}
Correct Answer

(A) Compile with error

[#47] 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)
}
}
Correct Answer

one

[#48] What is the output for the below code? public class A{
static{
System.out.println("static")
}
{
System.out.println("block")
}
public A(){
System.out.println("A")
}
public static void main(String[] args){
A a = new A()
}
}
Correct Answer

(B) static block A

Explanation

Solution: First execute static block, then statement block and then constructor.

[#49] What will be the output? public class Test{
public static void main(String[] args){
String value = "abc"
changeValue(value)
System.out.println(value)
}
public static void changeValue(String a){
a = "xyz"
}
}
Correct Answer

(A) abc

Explanation

Solution: Java pass reference as value. passing the object reference, and not the actual object itself. Simply reassigning to the parameter used to pass the value into the method will do nothing, because the parameter is essentially a local variable.

[#50] What will be the output for the below code? public class Test{
static{
int a = 5
}
public static void main(String[] args){
System.out.println(a)
}
}
Correct Answer

(A) Compile with error

Explanation

Solution: A variable declared in a static initializer is not accessible outside its enclosing block.