File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes int    VS       Integer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply locked New topic

int VS Integer

Suresh Rajadurai
Ranch Hand

Joined: Feb 22, 2007
Posts: 58
Hi Gurus,

Can anybody tell me the difference between "int" and "Integer" ?
What is the difference between the declarations:

int i;
Integer i;

many thanks,

Freddy Wong
Ranch Hand

Joined: Sep 11, 2006
Posts: 959

int is a primitive data type and Integer is a wrapper class.

Since Java 5, you can perform autoboxing, e.g.
int i = new Integer(5); or
Integer i = 5;

Hope this helps.

SCJP 5.0, SCWCD 1.4, SCBCD 1.3, SCDJWS 1.4
My Blog
Jinny Morris
Ranch Hand

Joined: Apr 29, 2007
Posts: 101
Suresh -

An int is a "simple" primitive data type; its use in Java is pretty much the same as it is in other languages. An Integer is an actual class; a "wrapper" for the primitive int type for situations where you might need to use an object rather than a primitive.

A good discussion of the primitives and their associated wrapper classes is given in the Sun online tutorial here:
[ August 27, 2007: Message edited by: Jinny Morris ]
lei feng

Joined: Aug 23, 2007
Posts: 26
sometimes if you want to cast int to String, you must use the wrapper class integer to get it. for example
int i=5;
String s=Integer.toString(5);
or inverse cast:
String s="5";
int i=Integer.parseInt(s);
i always use the integer in casting type.....
you also can cast int to Integer or inverse.
int i=5;
Integer in=new Integer(i);
inverse cast
Integer in=new Integer(5);
int i=in.intValue();
generally data passing must be using Class.......and int/long/double is not a Class....
[ August 28, 2007: Message edited by: lei feng ]
Saurabh Patil
Ranch Hand

Joined: Dec 11, 2005
Posts: 47

Java provides wrapper classes to most of its primitive data types. Wrapper classes are nothing special they are normal classes with a place for primitive data type it represents along with some methods which act on its datatype. And there are times when we need these methods and hence some times we need to use wrapper classes instead of primitive data type. Another benefit is that primitive data types are not objects by themselves, but when you embed your primitive data type into its respective wrapper class you can create object and pass it, - useful when we need to pass an object to any method.

hope this helps..

Preparing for OCPJWCD 6.
I agree. Here's the link:
subject: int VS Integer
It's not a secret anymore!