Well, it depends.
With the second case, value
would be populated with its default value of 0
, only to be reassigned at instantiation with 100
. In the first case, value
is just instantly given the value of 100
.
Semantically, this would help a programmer - they would see that this particular value means something a little more than just it being arbitrary (although, it should be a constant value somewhere).
Programmatically, there's no pain if a primitive is set to some initial value. It means that there's something in there for you to use, and if your program depends on there being a non-negative or false value, by George it will work.
Things get more explicit when dealing with object references. Take, for instance, these two classes:
public class Foo {
List<String> elements;
public Foo() {
}
public Foo(String... items) {
elements = new ArrayList<>();
for(String item : items) {
elements.add(item);
}
}
}
public class Bar {
List<String> elements = new ArrayList<>();
public Bar() {
}
public Bar(String... items) {
for(String item : items) {
elements.add(item);
}
}
}
There are intentionally no-arg constructors to hammer home the point - for Foo
, if I attempt to use elements
, then I'm in a bit of trouble if I don't use the appropriate constructor - elements
is null
!* I could then just instantiate it whenever I needed it, but I would very much want to avoid destroying a potentially newed and populated list.
That means a lot of code looking something like this:
if(elements == null) {
elements = new ArrayList<>();
}
...then I have to worry about it being thread safe. Sheesh, talk about a hassle.
With Bar
, I'm guaranteed that at instantiation, there is an instance of a list in elements
, so I don't have to worry about it being null
.**
This is known as eager instantiation. You really don't want to live without that object, so why wait until you think you need it (or lazily instantiate)?
*: The default value for all reference types is null
.
**: You do have to worry about that being overwritten, but that's a concern outside of the scope of this question.