Site icon NgDeveloper

[Clearly explained] int Vs Integer

int(primitive data type) and Integer (wrapper class object):

1. It is not possible to assign null (no value) to int. But the same possible in Integer.
Eg:

[java]Integer a = null; // Possible
int ab = null; //Not Possible[/java]

 

2. In collections we can able to use Integer for HashMap (key) or vector(Integer) or ArrayList(Integer), int cannot be used in collections.
Eg:

[java]List<Integer> myList = new ArrayList<Integer>(); //Possible
List<int> myList = new ArrayList<int>(); // Not possible

HashMap<Integer,String> myMap = new HashMap<Integer, String>(); //Possible
HashMap<int,String> myMapInt = new HashMap<int, String>(); // Not possible

Vector<Integer> myVector = new Vector<Integer>(); //Possible
Vector<int> myVectorInt = new Vector<int>(); //Not possible[/java]

 

3. If we want to use methods like toString(), doubleValue(), byteValue(),floatValue(), longValue(), shortValue() etc…, then we must have Integer(wrapper) not int (primitive).

Eg:

[java]Integer firstVariableNewInteger = new Integer(10);
Integer secondVariableNewInteger = new Integer(6).

System.out.println(firstVariableNewInteger .doubleValue()); //Possible

int firstVar = 10;
int secondVar = 6;</pre>
System.out.println(firstVar.doubleValue()); // Not possible [/java]

Exit mobile version