As the title says, what exactly is the difference between
public static String myString = \"Hello World!\";
and
public stat
To continue with what Scott Stanchfield wrote, you can use the Collections.unmodifiableXXX()
methods for safety, though libraries like Google Guava may make that less necessary. Consider:
public static final Map CAPITALS;
static {
Map map = new HashMap<>(); //Java 7.
map.put("NY", "Albany");
map.put("MD", "Annapolis");
map.put("VA", "Richmond");
map.put("CT", "Hartford");
// 46 more states
CAPITALS = Collections.unmodifiableMap(map);
}
Of course, having a 52-line static block may be disorienting, and so you might instead take the static block and turn it into a static method.
public static final Map CAPITALS = capitals();
private static Map capitals() {
Map map = new HashMap<>(); //Java 7.
map.put("NY", "Albany");
map.put("MD", "Annapolis");
map.put("VA", "Richmond");
map.put("CT", "Hartford");
// 46 more states
return Collections.unmodifiableMap(map);
}
The difference is a matter of style. You might instead just work with a database table.