Bookmark Topic Watch Topic
  • New Topic

int VS Integer

 
Suresh Rajadurai
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Report post to moderator
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,

Suresh.
 
Freddy Wong
Ranch Hand
Posts: 959
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Report post to moderator
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.
 
Jinny Morris
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Report post to moderator
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: http://java.sun.com/docs/books/tutorial/java/data/numberclasses.html
[ August 27, 2007: Message edited by: Jinny Morris ]
 
lei feng
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Report post to moderator
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
Posts: 48
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Report post to moderator
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..
 
    Bookmark Topic Watch Topic
  • New Topic