Monday, 1 June 2020

Key differences between java int and Integer

Hi, lets see one of the favourites question every interviewer asks, at the time of interview. In java int and Integer, both are used to store integer values. Integer is an object while int is not an object it is a data type. Integer is a class and it has various methods for manipulating, storing the data, and doing things to Integer.

int

◈   int is a primitive data type. Primitive data types are basic data types used by the programmers to create variables in their programs.

◈   Primitive data types start with small letters.

◈   int can never be null. Int data type used to store integer binary values only.

◈   We can not change its value or syntax.

Integer

◈   Integer is a wrapper class. Wrapper class encapsulates or wraps primitive data types (eg. int, char, byte, etc.,).

◈   Wrapper classes start with a capital letter even all the predefined classes in java start with a capital letter.

◈   Integer can be null i.e. we can assign a reference variable of Integer to null. It can throw NullPointerException if you are performing auto-boxing to convert Integer to int or vice-versa.

◈   Since Integer is a wrapper class, it can call several in-built methods defined in the class.

◈   Integer class helps us to convert int data object and to convert the object into int as per programmers requirement.

◈   By using Integer class, we can perform several operations like reverse(), rotateLeft(), rotateRight().

In java, every primitive type has an equivalent wrapper class. These are as follows:

Primitive data type Wrapper class  
int  Integer
char Character
float Float
byte Byte
short Short
long Long
double Double
boolean Boolean

Example of Integer vs int

No comments:

Post a Comment