public class Test {
private int var1 = 1;
// These are the troublesome lines
public String[] name = new String[10];
// Use a constructor for initialization or
// declare the string array as public String[] name = {"Mary" };
public Test() {
name[0] = "Mary"; // When I remove this line, both the errors go away
}
public int var2 = 10;
}
In java you have to put statements into methods/blocks.
For example
public class TestB {
public String[] s = new String[10];
{
s[0] = "10";
}
}
is actually legal (but I wouldn't use it, except maybe for static members)
EDIT: Clarification about static members
Often we have to use pure static objects, in such cases an easy way to provide initialization, is to use an anonymous static block. Something like:
public class TestStatic {
private String [] someStaticStringArray = new String [10];
static {
someStaticStringArray[0] = "foo";
someStaticStringArray[1] = "bar";
}
// Or better with static HashMaps
private static HashMap<String, String> hm = new HashMap<String, String>();
static {
hm.put("key", "val");
hm.put("key2", "val2");
hm.put("key3", "val3");
}
}
For static data members, when I've got no way to provide a factory method or a factory object, I use this way. For non static data members I prefer using constructors, even thou the anonymous block works.
There are many ways to provide initialization in java, I guess personal taste is the main reason for choosing one over another.
For your particular situation I'd go for something like this:
public class TestC {
// Static data member, constructor does not read data from XML
private static YourDataObject obj = new YourDataObject();
public static YourDataObject getInstance(String xmlFile) {
// Read XML file
// Actually initialize the instance
obj.set...(); //
// return the instance
return obj;
}
}