270
votes

I was reading More Joel on Software when I came across Joel Spolsky saying something about a particular type of programmer knowing the difference between an int and an Integer in Java/C# (Object-Oriented Programming Languages).

So, what is the difference?

26
C# doesn't have an Integer type.Judah Gabriel Himango

26 Answers

253
votes

In Java, the 'int' type is a primitive, whereas the 'Integer' type is an object.

In C#, the 'int' type is the same as System.Int32 and is a value type (ie more like the java 'int'). An integer (just like any other value types) can be boxed ("wrapped") into an object.


The differences between objects and primitives are somewhat beyond the scope of this question, but to summarize:

Objects provide facilities for polymorphism, are passed by reference (or more accurately have references passed by value), and are allocated from the heap. Conversely, primitives are immutable types that are passed by value and are often allocated from the stack.

155
votes

Well, in Java an int is a primitive while an Integer is an Object. Meaning, if you made a new Integer:

Integer i = new Integer(6);

You could call some method on i:

String s = i.toString();//sets s the string representation of i

Whereas with an int:

int i = 6;

You cannot call any methods on it, because it is simply a primitive. So:

String s = i.toString();//will not work!!!

would produce an error, because int is not an object.

int is one of the few primitives in Java (along with char and some others). I'm not 100% sure, but I'm thinking that the Integer object more or less just has an int property and a whole bunch of methods to interact with that property (like the toString() method for example). So Integer is a fancy way to work with an int (Just as perhaps String is a fancy way to work with a group of chars).

I know that Java isn't C, but since I've never programmed in C this is the closest I could come to the answer. Hope this helps!

Integer object javadoc

Integer Ojbect vs. int primitive comparison

39
votes

I'll add to the excellent answers given above, and talk about boxing and unboxing, and how this applies to Java (although C# has it too). I'll use just Java terminology because I am more au fait with that.

As the answers mentioned, int is just a number (called the unboxed type), whereas Integer is an object (which contains the number, hence a boxed type). In Java terms, that means (apart from not being able to call methods on int), you cannot store int or other non-object types in collections (List, Map, etc.). In order to store them, you must first box them up in its corresponding boxed type.

Java 5 onwards have something called auto-boxing and auto-unboxing which allow the boxing/unboxing to be done behind the scenes. Compare and contrast: Java 5 version:

Deque<Integer> queue;

void add(int n) {
    queue.add(n);
}

int remove() {
    return queue.remove();
}

Java 1.4 or earlier (no generics either):

Deque queue;

void add(int n) {
    queue.add(Integer.valueOf(n));
}

int remove() {
    return ((Integer) queue.remove()).intValue();
}

It must be noted that despite the brevity in the Java 5 version, both versions generate identical bytecode. Thus, although auto-boxing and auto-unboxing are very convenient because you write less code, these operations do happens behind the scenes, with the same runtime costs, so you still have to be aware of their existence.

Hope this helps!

29
votes

I'll just post here since some of the other posts are slightly inaccurate in relation to C#.

Correct: int is an alias for System.Int32.
Wrong: float is not an alias for System.Float, but for System.Single

Basically, int is a reserved keyword in the C# programming language, and is an alias for the System.Int32 value type.

float and Float is not the same however, as the right system type for ''float'' is System.Single. There are some types like this that has reserved keywords that doesn't seem to match the type names directly.

In C# there is no difference between ''int'' and ''System.Int32'', or any of the other pairs or keywords/system types, except for when defining enums. With enums you can specify the storage size to use and in this case you can only use the reserved keyword, and not the system runtime type name.

Wether the value in the int will be stored on the stack, in memory, or as a referenced heap object depends on the context and how you use it.

This declaration in a method:

int i;

defines a variable i of type System.Int32, living in a register or on the stack, depending on optimizations. The same declaration in a type (struct or class) defines a member field. The same declaration in a method argument list defines a parameter, with the same storage options as for a local variable. (note that this paragraph is not valid if you start pulling iterator methods into the mix, these are different beasts altogether)

To get a heap object, you can use boxing:

object o = i;

this will create a boxed copy of the contents of i on the heap. In IL you can access methods on the heap object directly, but in C# you need to cast it back to an int, which will create another copy. Thus, the object on the heap cannot easily be changed in C# without creating a new boxed copy of a new int value. (Ugh, this paragraph doesn't read all that easily.)

21
votes

Regarding Java 1.5 and autoboxing there is an important "quirk" that comes to play when comparing Integer objects.

In Java, Integer objects with the values -128 to 127 are immutable (that is, for one particular integer value, say 23, all Integer objects instantiated through your program with the value 23 points to the exact same object).

Example, this returns true:

Integer i1 = new Integer(127);
Integer i2 = new Integer(127);
System.out.println(i1 == i2); //  true

While this returns false:

Integer i1 = new Integer(128);
Integer i2 = new Integer(128);
System.out.println(i1 == i2); //  false

The == compares by reference (does the variables point to the same object).

This result may or may not differ depending on what JVM you are using. The specification autoboxing for Java 1.5 requires that integers (-128 to 127) always box to the same wrapper object.

A solution? =) One should always use the Integer.equals() method when comparing Integer objects.

System.out.println(i1.equals(i2)); //  true

More info at java.net Example at bexhuff.com

20
votes

In Java there are two basic types in the JVM. 1) Primitive types and 2) Reference Types. int is a primitive type and Integer is a class type (which is kind of reference type).

Primitive values do not share state with other primitive values. A variable whose type is a primitive type always holds a primitive value of that type.

int aNumber = 4;
int anotherNum = aNumber;
aNumber += 6;
System.out.println(anotherNum); // Prints 4

An object is a dynamically created class instance or an array. The reference values (often just references) are pointers to these objects and a special null reference, which refers to no object. There may be many references to the same object.

Integer aNumber = Integer.valueOf(4);
Integer anotherNumber = aNumber; // anotherNumber references the 
                                 // same object as aNumber

Also in Java everything is passed by value. With objects the value that is passed is the reference to the object. So another difference between int and Integer in java is how they are passed in method calls. For example in

public int add(int a, int b) {
    return a + b;
}
final int two = 2;
int sum = add(1, two);

The variable two is passed as the primitive integer type 2. Whereas in

public int add(Integer a, Integer b) {
    return a.intValue() + b.intValue();
}
final Integer two = Integer.valueOf(2);
int sum = add(Integer.valueOf(1), two);

The variable two is passed as a reference to an object that holds the integer value 2.


@WolfmanDragon: Pass by reference would work like so:

public void increment(int x) {
  x = x + 1;
}
int a = 1;
increment(a);
// a is now 2

When increment is called it passes a reference (pointer) to variable a. And the increment function directly modifies variable a.

And for object types it would work as follows:

public void increment(Integer x) {
  x = Integer.valueOf(x.intValue() + 1);
}
Integer a = Integer.valueOf(1);
increment(a);
// a is now 2

Do you see the difference now?

11
votes

In C#, int is just an alias for System.Int32, string for System.String, double for System.Double etc...

Personally I prefer int, string, double, etc. because they don't require a using System; statement :) A silly reason, I know...

10
votes

There are many reasons to use wrapper classes:

  1. We get extra behavior (for instance we can use methods)
  2. We can store null values whereas in primitives we cannot
  3. Collections support storing objects and not primitives.
8
votes

This has already been answered for Java, here's the C# answer:

"Integer" is not a valid type name in C# and "int" is just an alias for System.Int32. Also, unlike in Java (or C++) there aren't any special primitive types in C#, every instance of a type in C# (including int) is an object. Here's some demonstrative code:

void DoStuff()
{
    System.Console.WriteLine( SomeMethod((int)5) );
    System.Console.WriteLine( GetTypeName<int>() );
}

string SomeMethod(object someParameter)
{
    return string.Format("Some text {0}", someParameter.ToString());
}

string GetTypeName<T>()
{
    return (typeof (T)).FullName;
}
8
votes

One more thing that I don't see in previous answers: In Java the primitive wrappers classes like Integer, Double, Float, Boolean... and String are suposed to be invariant, so that when you pass an instance of those classes the invoked method couldn't alter your data in any way, in opositión with most of other classes, which internal data could be altered by its public methods. So that this classes only has 'getter' methods, no 'setters', besides the constructor.

In a java program String literals are stored in a separate portion of heap memory, only a instance for literal, to save memory reusing those instances

8
votes

int is used to declare primitive variable

e.g. int i=10;

Integer is used to create reference variable of class Integer

Integer a = new Integer();
8
votes

In platforms like Java, ints are primitives while Integer is an object which holds a integer field. The important distinction is that primitives are always passed around by value and by definition are immutable.

Any operation involving a primitive variable always returns a new value. On the other hand, objects are passed around by reference. One could argue that the point to the object (AKA the reference) is also being passed around by value, but the contents are not.

7
votes

have you ever programmed before then (int) is one of the primitive types you can set for your variables (just like char, float, ...).

but Integer is a wrapper class that you can use it to do some functions on an int variable (e.g convert it to string or vise versa,...) , but keep note that methods in the wrapper classes are static so you can use them anytime without creating an instance of Integer class. as a recap :

int x;
Integer y; 

x and y are both variables of type int but y is wrapped by an Integer class and has several methods that you use,but i case you need to call some functions of Integer wrapper class you can do it simply.

Integer.toString(x);

but be aware that both x and y are corect but if you want to use them just as a primitive type, use the simple form (used for defining x).

7
votes

Java:

int, double, long, byte, float, double, short, boolean, char - primitives. Used for hold the basic data types supported by the language. the primitive types are not part of the object hierarchy, and they do not inherit Object. Thet can'be pass by reference to a method.

Double, Float, Long, Integer, Short, Byte, Character, and Boolean, are type Wrappers, packaged in java.lang. All of the numeric type wrappers define constructors that allow an object to be constructed from a given value, or a string representation of that value. Using objects can add an overhead to even the simplest of calculations.

Beginning with JDK 5, Java has included two very helpful features: autoboxing and autounboxing. Autoboxing/unboxing greatly simplifies and streamlines code that must convert primitive types into objects, and vice versa.

Example of constructors:

Integer(int num)
Integer(String str) throws NumberFormatException
Double(double num)
Double(String str) throws NumberFormatException

Example of boxing/unboxing:

class ManualBoxing {
        public static void main(String args[]) {
        Integer objInt = new Integer(20);  // Manually box the value 20.
        int i = objInt.intValue();  // Manually unbox the value 20
        System.out.println(i + " " + iOb); // displays 20 20
    }
}

Example of autoboxing/autounboxing:

class AutoBoxing {
    public static void main(String args[]) {
        Integer objInt = 40; // autobox an int
        int i = objInt ; // auto-unbox
        System.out.println(i + " " + iOb); // displays 40 40
    }
}

P.S. Herbert Schildt's book was taken as a reference.

4
votes

An int variable holds a 32 bit signed integer value. An Integer (with capital I) holds a reference to an object of (class) type Integer, or to null.

Java automatically casts between the two; from Integer to int whenever the Integer object occurs as an argument to an int operator or is assigned to an int variable, or an int value is assigned to an Integer variable. This casting is called boxing/unboxing.

If an Integer variable referencing null is unboxed, explicitly or implicitly, a NullPointerException is thrown.

4
votes

An int and Integer in Java and C# are two different terms used to represent different things. It is one of the the primitive data types that can be assigned to a variable that can store exactly. One value of its declared type at a time.

For example:

int number = 7;

Where int is the datatype assigned to the variable number which holds the value seven. So an int is just a primitive not an object.

While an Integer is a wrapper class for a primitive data type which has static methods. That can be used as an argument to a method which requires an object, where as int can be used as an argument to a method which requires an integer value, that can be used for arithmetic expression.

For example:

Integer number = new Integer(5);
4
votes

In both languages (Java and C#) int is 4-byte signed integer.

Unlike Java, C# Provides both signed and unsigned integer values. As Java and C# are object object-oriented, some operations in these languages do not map directly onto instructions provided by the run time and so needs to be defined as part of an object of some type.

C# provides System.Int32 which is a value type using a part of memory that belongs to the reference type on the heap.

java provides java.lang.Integer which is a reference type operating on int. The methods in Integer can't be compiled directly to run time instructions.So we box an int value to convert it into an instance of Integer and use the methods which expects instance of some type (like toString(), parseInt(), valueOf() etc).

In C# variable int refers to System.Int32.Any 4-byte value in memory can be interpreted as a primitive int, that can be manipulated by instance of System.Int32.So int is an alias for System.Int32.When using integer-related methods like int.Parse(), int.ToString() etc. Integer is compiled into the FCL System.Int32 struct calling the respective methods like Int32.Parse(), Int32.ToString().

4
votes

In Java, the int type is a primitive data type, where as the Integer type is an object.

In C#, the int type is also a data type same as System.Int32. An integer (just like any other value types) can be boxed ("wrapped") into an object.

3
votes

In Java int is a primitive data type while Integer is a Helper class, it is use to convert for one data type to other.

For example:

double doubleValue = 156.5d;
Double doubleObject  = new Double(doubleValue);
Byte myByteValue = doubleObject.byteValue ();
String myStringValue = doubleObject.toString();

Primitive data types are store the fastest available memory where the Helper class is complex and store in heep memory.

reference from "David Gassner" Java Essential Training.

2
votes

"int" is primitive data-type and "Integer" in Wrapper Class in Java. "Integer" can be used as an argument to a method which requires an object, where as "int" can be used as an argument to a method which requires an integer value, that can be used for arithmetic expression.

1
votes

01. Integer can be null. But int cannot be null.

Integer value1 = null; //OK

int value2 = null      //Error

02. Only can pass Wrapper Classes type values to any collection class.

(Wrapper Classes - Boolean,Character,Byte,Short,Integer,Long,Float,Double)

List<Integer> element = new ArrayList<>();
int valueInt = 10;
Integer  valueInteger = new Integer(value);
element.add(valueInteger);

But normally we add primitive values to collection class? Is point 02 correct?

List<Integer> element = new ArrayList<>();
element.add(5);

Yes 02 is correct, beacouse autoboxing.

Autoboxing is the automatic conversion that the java compiler makes between the primitive type and their corresponding wrapper class.

Then 5 convert as Integer value by autoboxing.

1
votes

int is predefined in library function c# but in java we can create object of Integer

0
votes

In java as per my knowledge if you learner then, when you write int a; then in java generic it will compile code like Integer a = new Integer(). So,as per generics Integer is not used but int is used. so there is so such difference there.

0
votes

int is a primitive data type. Integer is a wrapper class. It can store int data as objects.

0
votes

int is a primitive datatype whereas Integer is an object. Creating an object with Integer will give you access to all the methods that are available in the Integer class. But, if you create a primitive data type with int, you will not be able to use those inbuild methods and you have to define them by yourself. But, if you don't want any other methods and want to make the program more memory efficient, you can go with primitive datatype because creating an object will increase the memory consumption.

0
votes

(Java Version) In Simple words int is primitive (cannot have null value) and Integer is wrapper object for int.

One example where to use Integer vs int, When you want to compare and int variable again null it will throw error.

int a;
//assuming a value you are getting from data base which is null
if(a ==null) // this is wrong - cannot compare primitive to null
{
do something...}

Instead you will use,
Integer a;
//assuming a value you are getting from data base which is null
if(a ==null) // this is correct/legal
{ do something...}