Reputation: 30511
Why does this work while the other throws errors:
import java.util.*;
//This works fine
public class ArrayTest {
public static String[] names = {"James", "John", "Mark"};
public static void main( String args[] ){
System.out.print("Names: " + Arrays.toString(names));
}
}
//But why does this not?
public class ArrayTest {
public static String[] names = new String[3];
names[0] = "James";
names[1] = "John";
names[2] = "Mark";
public static void main( String args[] ){
System.out.print("Names: " + Arrays.toString(names));
}
}
Upvotes: 2
Views: 258
Reputation: 3520
The simple reason :
You cannot execute instructions in the declaration of the class, unless you use a static block such as :
static { names[0] = "James"; names[1] = "John"; names[2] = "Mark"; }
But be aware that a static block is executed once, when the class is loaded by the Java virtual machine.
Therefore, if you create several instances of your class, the static block will still only be executed once.
Upvotes: 0
Reputation: 533860
A syntax I like is as follows (esp. for long lists)
public static final String[] names = "James,John,Mark".split(",");
Upvotes: 0
Reputation: 308998
Try it like this:
public class ArrayTest {
public static String[] names;
static
{
names = new String[3];
names[0] = "James";
names[1] = "John";
names[2] = "Mark";
}
public static void main( String args[] ){
System.out.print("Names: " + Arrays.toString(names));
}
}
Upvotes: 4
Reputation: 346486
The second is invalid syntax. A class declaration can contain only field definitions, method definitions, nested class definitions, and initializer blocks, but not plain statements like names[0] = "James";
Thus, you have to put those statements into a method (which can be called by a field initializer) or an initializer block.
Upvotes: 0
Reputation: 5023
You cannot assign values to the array in the class declaration. You have to do it in a body of a method, e.g. the main
method.
public class ArrayTest {
public static String[] names = new String[3];
public static void main( String args[] ) {
names[0] = "James";
names[1] = "John";
names[2] = "Mark";
System.out.print("Names: " + Arrays.toString(names));
}
}
Or do it in a static block like this:
public class ArrayTest {
public static String[] names = new String[3];
static {
names[0] = "James";
names[1] = "John";
names[2] = "Mark";
}
public static void main( String args[] ) {
System.out.print("Names: " + Arrays.toString(names));
}
}
Upvotes: 1
Reputation: 17898
Enclose the array init inside static init block like follows:
static {
names[0] = "James";
names[1] = "John";
names[2] = "Mark";
}
Upvotes: 1
Reputation: 5473
Put the initialization in a static block. Else it is run only when a object of that type is instantiated.
Upvotes: 0