I was going through a test on itester.org and found a question which I don't understand:
public class Runner
{
public static Integer i;
public static void main(String[] args)
{
if (i == 42) {
System.out.printf("wow");
}
}
}
I read before, that integer variable is assigned by default 0
. Why is it assigned null
here?
null can only be assigned to reference type, you cannot assign null to primitive variables e.g. int, double, float, or boolean.
The default value of Integer is 0.
Null is the default reference: In Java, all Java reference types have a common default value, the null reference. This reference appears in uninitialized array elements and field values of that type. The null reference is distinct from any reference that is produced by a new expression and/or a constructor call.
If no default value is declared explicitly, the default value is the null value. This usually makes sense because a null value can be considered to represent unknown data. In a table definition, default values are listed after the column data type.
Any reference type (i.e. any variable whose type is Object or a sub-class of Object) has a default value of null. This includes Integer
.
The primitive int
, on the other hand, has a default value of 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With