Computer Applications

Find the error:

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

Java Conditional Stmts

8 Likes

Answer

The variable y is declared inside 'if' block. Its scope is limited to if block and it cannot be used outside the block.

The correct code snippet is as follows:

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

Answered By

3 Likes


Related Questions