Examveda

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: Option D

Solution (By Examveda Team)

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

This Question Belongs to Java Program >> Data Types And Variables

Join The Discussion

Comments (1)

  1. Gabriel Joshua
    Gabriel Joshua:
    5 months 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

Related Questions on Data Types and Variables