I'm currently bored and was doing some Java practice tests since it's been quite some time I've programmed in Java. After a certain question I'm now wondering the differences between the following:
String[] test1 = { "A", "B", "C" };
String[] test2 = new String[]{ "A", "B", "C" };
String test3[] = { "A", "B", "C" };
String test4[] = new String[]{ "A", "B", "C" };
When I type this in a Java IDE I'm not getting any errors. I haven't tried to compile any of them yet (although I've mainly used test2 myself in the past, so I know that one works).
- So, does each of these compile?
- And if yes, what are the differences (if any)?
- (Is
test1better for performance thantest2because you don't make a newString[]-instantiation, or is this done anyway behind the scenes?) - (If
test1is the same astest3: Why doestest3andtest4exist in Java if it's the same astest1andtest2? Are there any cases where using[]behind the field-name is preferred above behind the type?) - (Are there more (almost similar) variants apart from these four?)
- (And other questions like these.)
Just want to know out of curiosity. We learn something new every day I guess.
[]after the field-name instead of the type? It's certainly new (and pretty counter-intuitive) for me personally..