can i initialize an array outside the method just like we initialize a member/field variable
i want to initialize the array at the instance level but i am not able to initialize here is the code
public class Arrays {
/** Creates a new instance of Arrays */
int []arr2=new int[2];
arr2[0]=20;//error at compile time
arr2[1]=30;//error
public Arrays() { }
public static void main(String []args)
{
System.out.println("Element at 0th position is "+arr2开发者_开发技巧[0]);
System.out.println("Element at 1th position is "+arr2[1]);
}
}
if you want to initilize while declaring it as class member do it like this
class MyClass{
int []arr2={20,30};
}
following is a statement, you can't write statement at the place you are trying to do
arr2[0]=20;//error at compile time
This is the way to initialize
int[] arr2 = { 20, 30 };
For completeness, not prettiness, the following will work:
public class Arrays {
int []arr2=new int[2];
// this is a field definition
{ // and this is a dynamic initializer,
// it runs after the constructor's
// first line
arr2[0]=20;
arr2[1]=30;
}
}
But of course it's better practice to initialize the array as shown in the other answers.
And to answer the question:
at Class level, only the following are allowed:
- Constructor definitions
- Method definitions
- Inner class definitions (including interfaces and enums)
- Field definitions
- Initializer blocks (static or dynamic / instance)
Statements are not allowed, they must be nested inside one of the above.
Regarding Adriaan Koster's comment:
They are called instance initializer blocks. The opposite of 'static' is 'instance' in OO, not 'dynamic'.
True, instance is the better OO term. But linguistically, dynamic is the opposite of static, so I'll stick with dynamic.
Instance initializer blocks are copied into each constructor by the compiler and run BEFORE the constructor code, not after.
Actually, they are copied into the constructor after the first line (the implicit or explicit this()
or super()
call). So technically we are either both right or both wrong (the initializer runs AFTER the first line and BEFORE the rest).
For clarification (regarding the first line):
- Every class has at least one constructor. If you don't add one the compiler adds a public constructor with no arguments.
- Every constructor begins with a call to either another constructor of the same class
this(args)
or a constructor of the super class (super(args)
). If you don't write one of these lines, the compiler inserts asuper()
call without parameters. So every constructor has at least one statement. And initializers are run after that initial statement.
Reference:
- Initializing Fields (Sun Java Tutorial)
Code like arr2[0]=20;
cannot be placed at the class level, it has to be inside a method, or code block. Fortunately Java allows int [] arr = {20, 10};
精彩评论