Wednesday 11 March 2020

Integer vs int

a. int is a primitive type, whereas Integer is a reference type. More specifically Integer is a wrapper type of int type. Every primitive type in Java has corresponding wrapper type.
         byte has Byte
         short has Short
         int has Integer
         long has Long
         float has Float
         double has Double
         boolean has Boolean
         char has Character

b. Default value of int field is 0, whereas default value of Integer is null.

DemoClass.java
package com.sample.app;

public class DemoClass {
 int primitiveField;
 Integer objField;
}

App.java
package com.sample.app;

public class App {

 public static void main(String[] args) {
  DemoClass demoClass = new DemoClass();

  System.out.println("primitiveVariable : " + demoClass.primitiveField);
  System.out.println("objVariable : " + demoClass.objField);
 }

}

Output
primitiveVariable : 0
objVariable : null

c. By default int variables are mutable (unless you define it with via final modifier), whereas Integer variables are immutable.

d. Since Integer is a reference type, you can use it as a type in collections, but you can’t use int as a type in collecitons.

Example
List<Integer> list = new ArrayList<> ();
Map<Integer, String> map = new HashMap<> ();

e. Integer can allow null values, but int do not allow.

f. Performing Arithmetic operations on ‘int’ are always faster than ‘Integer’.

g. == operator is used to check equality of two ‘int’ variables, where as ‘equals’ method is used to check whether two integer objects has same int value or not.

h. Since ‘int’ is a primitive type, no methods are associated with it. Whereas Integer is a class, methods are associated with it.

Example
Integer i1 = new Integer(10);
i1.intValue();
i1.toString();

You may like

No comments:

Post a Comment