Examveda
Examveda

Determine output:
class A{
        public static void main(String args[]){
	        int x;
 	        x = 10;
	        if(x == 10){
		        int y = 20;
		        System.out.print("x and y: "+ x + " " + y);
		        y = x*2;
	        }
	        y = 100;
	        System.out.print("x and y: " + x + " " + y);
        }
}

A. 10 20 10 100

B. 10 20 10 20

C. 10 20 10 10

D. Error

Answer: Option D

Solution(By Examveda Team)

The code defines a class A with a main method.
Inside the main method:
- An integer variable x is declared and assigned the value 10.
- There's an if statement that checks if x is equal to 10. This condition is true.
- Inside the if block:
- Another integer variable y is declared and assigned the value 20.
- The program prints "x and y: 10 20" using System.out.print.
- The value of y is updated to x * 2, which is 20.
- Outside the if block:
- The program attempts to update the value of y to 100. However, this line causes a compilation error because the variable y was declared inside the if block and is not accessible outside of it.
- The program also attempts to print "x and y: 10 100". This line also causes a compilation error because the variable y is not in scope at this point.

So, the correct answer is "Error" because the code contains compilation errors due to the variable y being declared within the if block and not being accessible outside of it. The program cannot find the symbol y outside of the if block, leading to compilation errors.

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

Join The Discussion

Comments ( 2 )

  1. Himanshu Yadav
    Himanshu Yadav :
    4 years ago

    class Test1 {
    public
    static void main(String[] args)
    {
    int x = 20;
    System.out.println(x);
    }
    static
    {
    int x = 10;
    System.out.print(x + " ");
    }
    }


  2. Sachin Dandge
    Sachin Dandge :
    7 years ago

    variable declared inside the block,method,or constructors are considered as local variable hence we cant access it outside of all above and if we then we will get compile time error.

Related Questions on Data Types and Variables