Why is the Integer variable null by default?

I took a test on itester.org and found a question that I do not understand:

public class Runner { public static Integer i; public static void main(String[] args) { if (i == 42) { System.out.printf("wow"); } } } 

I read earlier that an integer variable is assigned a default of 0 . Why is null assigned here?

+5
source share
6 answers

Any reference type (i.e., any variable whose type is an object or a subclass of an object) has a default value of null. This includes Integer .

On the other hand, the int primitive has a default value of 0.

+7
source

Because JLS 4.12.5. The initial values โ€‹โ€‹of the variables are :

For all types of links ( ยง4.3 ), the default value is null.

And since Integer is a reference type, it gets null :

 ReferenceType: ClassOrInterfaceType TypeVariable ArrayType 

See link for other types.

+5
source

The original int type is set to 0 by default, but the default value for an Integer reference is null. Integer is a wrapper class - it is an object, not a primitive type.

You can read about autoboxing and unboxing in Java, the process by which Java automatically converts between primitive types and wrapper classes.

+5
source

In Java, Integer is an object type. In this code example, you need a primitive type, which is an int. In Java, any type of object type / reference type or any variable of type Sub of an object type that is not automatically initialized is initialized to zero. Where as a primitive type has a default value.

The reason for this is because Objects provide tools for polymorphism, are passed by reference (or, more precisely, have links passed by value), and are allocated from the heap. Conversely, primitives are immutable types that are passed by value and are often allocated from the stack.

+3
source

All non-primitive non-local variables are null unless explicitly assigned.

+1
source

An integer is a wrapper class, and in this code example, I am a reference variable. (In java, everything is not an object, so we use wrapper classes so that the object and java do boxing and unboxing). All reference variables in java are null by default and all primitive types have a default value (e.g. int i โ†’ 0)

Usage: - Private static int; then it has a value of 0 by default.

+1
source

Source: https://habr.com/ru/post/1207970/


All Articles