// Given the following code snippet:
public class VariableScope {
public static void main(String[] args) {
int x = 5;
int y = 10;
int z = 15;
if (x < 10) {
int y = 20;
z = 25;
System.out.println("Inside if block: x = " + x + ", y = " + y + ", z = " + z);
}
System.out.println("Outside if block: x = " + x + ", y = " + y + ", z = " + z);
}
}
What is the output of the above code?
A. Inside if block: x = 5, y = 20, z = 25 Outside if block: x = 5, y = 10, z = 25
B. Inside if block: x = 5, y = 10, z = 25 Outside if block: x = 5, y = 10, z = 25
C. Inside if block: x = 5, y = 20, z = 15 Outside if block: x = 5, y = 10, z = 25
D. Inside if block: x = 5, y = 20, z = 25 Outside if block: x = 5, y = 10, z = 15
Choose the correct option (A, B, C, or D) and provide the reason behind your choice.
The correct option is C. Inside if block: x = 5, y = 20, z = 15 Outside if block: x = 5, y = 10, z = 25
Explanation:
x
is declared and initialized with the value 5 in the main
method.y
is declared and initialized with the value 10 in the main
method.z
is declared and initialized with the value 15 in the main
method.if
block, another variable y
is declared and initialized with the value 20. This y
variable is local to the if
block and has a different scope than the y
variable declared in the main
method.if
block, the value of z
is changed to 25.System.out.println
statement inside the if
block will print the values of x
, y
, and z
based on their current values, which are 5, 20, and 25, respectively.if
block, the System.out.println
statement will print the values of x
, y
, and z
based on their current values, which are unchanged from their initial values (5, 10, and 15, respectively).Inside if block: x = 5, y = 20, z = 15
Outside if block: x = 5, y = 10, z = 25