ExamVeda
Login
Home
Data Types and Variables
?

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
Correct Answer: Option D
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'.
Examveda
Question posted by Examveda
Community

Join the Discussion

1 Comment
Gabriel Joshua
Gabriel Joshua 2 years ago
The int y=6 was defined in another block , it won't be able to be accessed by another block of code since that y is not defined in the main block