1
What will be the output of the following Java program?
class variable_scope
{
public static void main(String args[])
{
int x;
x = 5;
{
int y = 6;
System.out.print(x + " " + y);
}
System.out.println(x + " " + y);
}
} Answer & Solution
Answer: Option
D
Solution:
The correct answer is D: Compilation error.
Here's why:
In Java, variables have a scope, which determines where they can be accessed in the code.
'x' is declared outside the inner block, so it's accessible both inside and outside the curly braces {}.
'y' is declared inside the inner block {}. This means 'y' is only accessible within that block.
The line 'System.out.println(x + " " + y);' is outside the inner block where 'y' is defined.
Therefore, the compiler will give an error because it cannot find a variable named 'y' in that scope.
The program will not compile because of the scope issue with the variable 'y'.
Here's why:
In Java, variables have a scope, which determines where they can be accessed in the code.
'x' is declared outside the inner block, so it's accessible both inside and outside the curly braces {}.
'y' is declared inside the inner block {}. This means 'y' is only accessible within that block.
The line 'System.out.println(x + " " + y);' is outside the inner block where 'y' is defined.
Therefore, the compiler will give an error because it cannot find a variable named 'y' in that scope.
The program will not compile because of the scope issue with the variable 'y'.