Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an Integer variable assigned null by default?

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?

like image 962
weluci Avatar asked Nov 30 '14 09:11

weluci


People also ask

Can Integer be assigned null?

null can only be assigned to reference type, you cannot assign null to primitive variables e.g. int, double, float, or boolean.

What is the default value for Integer?

The default value of Integer is 0.

Why is null the default value of an object in Java?

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.

Which has a default value of null?

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.


1 Answers

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.

like image 88
Eran Avatar answered Sep 17 '22 23:09

Eran