After seeing a question about this, and many college colleagues with doubts attached to it, I decided to ask this question.
- Type
int
can be equal tonull
?
After seeing a question about this, and many college colleagues with doubts attached to it, I decided to ask this question.
int
can be equal to null
? As well said in @pmargreff's response, int
under no circumstances will be null
.
But what if the variable of type int
is not initialized, what is the value of it anyway?
It depends, if the variable belongs to the class it is automatically initialized with the value 0
, if it is a variable of a method it will not be automatically initialized, for this condition it should be explicitly initialized in the code, otherwise it will not compile.
Similarly to the primitive type, reference variables of the Integer type of the class instance are also initialized, however as null
, whereas in the methods they face exactly the same situation as the primitive variable: no initialization is implicitly generated. compile if you try to access its value. Example:
public class TesteInt {
public static void main(String[] args) {
new TesteInt().teste();
}
int iInstancia;
Integer objInstancia;
public void teste() {
int iLocal;
Integer objLocal;
System.out.println(iInstancia);
System.out.println(objInstancia);
//System.out.println(iLocal); //erro de compilação
//System.out.println(objLocal); //erro de compilação
}
}
Output:
0
null
If the lines that indicate erro de compilação
are uncommented, in fact, the code will not be able to be compiled.
Short answer:
int
will never count as null
Long answer:
In java almost everything is an object, or Object
, but not everything, and what is not an object is a primitive type ( primitive
). And only objects can have the value null
.
The most summarized difference is that objects contain a reference to states and behaviors, ie variables and methods, respectively. And primitive types have only one value.
These are primitive types:
If we need to use primitive types as objects we have the class wrapper
, which transforms primitive types so that they can be used in situations where primitive types can not be operated, just objects. An example of this is collections (class Collections
) that only operate objects.
The above information may be contradictory if you have already created and / or manipulated some type of collection using primitive types. This is because java has a feature called Autoboxing and Unboxing
, which does the automatic conversion when we are using primitive types but we could only use objects. That is, it calls the class wrapper
automatically.
Example:
java.util.Stack<Integer> pilha = new Stack();
int num = 10;
pilha.push(num);
The value for num
can not be null
even after insertion in the stack, because it was inserted in the stack was an equivalent object (in this case a Integer
) and num
remains a% with%.
Reference 1: Can an int be null in Java?