0

Why can I do:

public class ThisTest {
    int[] anArray  = new int[10];             
    public int[] getArr(){
        anArray[0] = 100;
        anArray[1] = 200;
        return anArray;                    
    } 
}

But not:

public class ThisTest {
    int[] anArray  = new int[10];     
    anArray[0] = 100;
    anArray[1] = 200;   
}
0

3 Answers 3

4

because you cannot assign values outside a method or a initialization block.

So this is also legal:

public class ThisTest {
    int[] anArray  = new int[10];     
    {     // This is the initialization block
        anArray[0] = 100;
        anArray[1] = 200;   
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You haven't declared a method. You can't just write code in the sky:)

1 Comment

@sshakir - A class consists basically of instance variables, methods, and constructors. You can't write code outside that:)
0

You probably want this:

public class ThisTest {
    int[] anArray  = new int[10];  

    public ThisTest()
    {   
        anArray[0] = 100;
        anArray[1] = 200;   
    }
}

The constructor is the appropriate place for the initialization you're doing. You can also use the initialization block as MByD shows, which is functionally equivalent to putting the statements at the beginning of your constructor (convenient if you are overloading the constructor and this initialization is common to all).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.