Mohammed Sajjad
Mohammed Sajjad

Reputation: 35

What will be the output of following Java program? And why I am getting error

I am getting error message if i execute the following program. It says o cannot be resolved to a variable.

public class Test {

    /**
* @param args
*/
    public static void main(String[] args) {

        try{
            int o[] = new int[2];
            o[3]=23;
            o[1]=33;
        }catch(Exception e){
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

        System.out.println(o[1]); //THis line shows the error.
    }

}

Why I am i getting in the line System.out.println(o[1]); ?

Upvotes: 0

Views: 99

Answers (3)

ninja.coder
ninja.coder

Reputation: 9658

The scope of your int o is limited to the try-catch block. Move it outside the try-catch block to access it in the sysout().

public static void main(String[] args) {
     /* Moved Outside */
     int o[] = new int[4];

        try{
            o[3] = 23;
            o[1] = 33;
        }catch(Exception e){
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

        /* o will be visible now */
        System.out.println(o[1]);
    }

Also, in order for o[3] = 23; to be executed, you will have to increase the array size to a minimum of 4.

Upvotes: 0

Tarinya88
Tarinya88

Reputation: 11

The problem is the scope. since you define o in the try block, the compiler doesn't know o outside of the try/catch. To Solve the Problem either put the print in a finally block or initialize o before the try block.

read more about variable scope here: http://www.java2s.com/Tutorial/Java/0020__Language/VariableScope.htm

Upvotes: 1

Frank
Frank

Reputation: 2066

First oft all you initialize o inside the try-block, so o is not visible outside of it. Changing this and calling o[3] will give an ArrayIndexOutOfBounds as o has only size of 2.

Upvotes: 1

Related Questions