// Consider the following Java code:
public class VariableExample {
public static void main(String[] args) {
int num1 = 5;
for(int i = 0; i < 3; i++) {
int num2 = num1 + i;
System.out.println("Value of num2: " + num2);
}
System.out.println("Value of num1: " + num1);
System.out.println("Value of num2: " + num2);
}
}
// What is the output of the above code and explain why?
a) Compilation error
b) It prints:
Value of num2: 5
Value of num2: 6
Value of num2: 7
Value of num1: 5
Compilation error
c) It prints:
Value of num2: 5
Value of num2: 6
Value of num2: 7
Value of num1: 5
Value of num2: 7
d) It prints:
Value of num2: 5
Value of num2: 6
Value of num2: 7
Value of num1: 5
Compilation error
The correct answer is d) It prints:
Value of num2: 5
Value of num2: 6
Value of num2: 7
Value of num1: 5
Compilation error
Explanation:
The variable num1
has a scope within the main
method, so it can be accessed throughout the method. Its initial value is 5.
Inside the for
loop, a new variable num2
is declared and assigned the value of num1 + i
. The scope of num2
is limited to the for
loop block. It exists only within the loop and cannot be accessed outside of it.
During each iteration of the loop, num2
is assigned a new value based on num1 + i
. It is then printed using the System.out.println
statement inside the loop. Thus, the output will be:
Value of num2: 5
Value of num2: 6
Value of num2: 7
After the for
loop, num1
is printed using System.out.println
. Since num1
is still in scope, its value remains the same and will be printed as 5:
Value of num1: 5
However, when we attempt to print num2
after the loop, a compilation error occurs. This is because num2
is only accessible within the for
loop block, and cannot be accessed outside of it. Hence, the code will not compile, and the output will be:
Compilation error
Therefore, option d) is the correct answer.