Vidyalelo
Java Programming · Q101

Data Types and Variables

Programming · Java Programming · question 101

Q101

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);

A.
5 6 5 6
B.
5 6 5
C.
Runtime error
D.
Compilation error
Answer

Answer: Option D

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'.