tags:

views:

5064

answers:

13

I was just sitting at my local Borders sipping coffee and reading (for free) 'More Joel on Software' when I came across Joel saying something about a particular type of programmer knowing the difference between an int and an Integer in Java/C# (Object Oriented Programming Languages). After a quick 'brain check,' I realized, to my dismay, that I didn't know the answer. Please help.

A: 

There's no such thing as an Integer in C. Don't you mean C#?

Michiel de Mare
+26  A: 

In object oriented languages such as Java and C#, the 'int' type is a primitive , whereas the 'Integer' type is 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, and are allocated from the heap. Conversely, primitives are passed by value and are allocated from the stack.

Matt
The statement that "objects [...] are passed by reference" is confusing and incorrect, IMO. It's more accurate to say that "Object references are passed by value." (Also primitives aren't always allocated from the stack - consider a primitive field within an object...)
Jon Skeet
In C# at least, int is a language keyword that is equivalent to the Int32 CLR (actually CTS) type.
Scott Dorman
@Jon Skeet i'm aware that you are seen as a C# Guru but due to the way the ENGLISH LANGUAGE works you can just say passed by reference as it is exatcly the same meaning not programming related. Yes I'm aware that passing by reference in C# just causes the reference to be passed by ref.
Tim Matthews
Sorry, the English language does not make "pass something by reference" and "pass a reference to something by value" equivalent statements, nor do these have equivalent meanings in a programming language context.
Alan Krueger
+14  A: 

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!

http://java.sun.com/j2se/1.3/docs/api/java/lang/Integer.html

http://mindprod.com/jgloss/intvsinteger.html

cmcculloh
in C# int is a synonym for Int32, see http://stackoverflow.com/questions/62503/c-int-or-int32-should-i-care
ripper234
+1  A: 

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...

huseyint
And it should be added, C#'s int/Int32 are *not* the same as Java's Integer.
Judah Himango
+9  A: 

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 is very convenient because you write less code, these operations do happen behind the scenes, with the same runtime costs, so you still have to be aware of their existence.

Hope this helps!

Chris Jester-Young
Deque isn't in java 1.5 or 1.4. It was added in 1.6.
Leo Izen
A: 

In Java and C#, int is a data type while Integer is a class that wraps the int data type into an object. This helps in passing integer values to methods that expect objects as parameter.

There are many other examples for this. For example, double (data type) and Double (class), float and Float etc...

Niyaz
Integer doesn't exist in C#. C# has no direct equivalent to Java's Integer. The closest would be assigning an int to an object.
Judah Himango
+8  A: 

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.)

Lasse V. Karlsen
+1  A: 

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;
}
Wedge
To be clear, in C#, int as well as System.Int32 are not objects. They are value types and treated much differently by the CLR than objects.
Peter Meyer
Actually, in C# Int32 is an object. It is a valuetype struct object that derives from system.object. It is not treated especially differently from other value objects as an "int" would be in Java.
Wedge
+3  A: 

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

Andreas H.R. Nilsson
Objects created with the new operator will always return false when compared with ==. Andreas is confusing Integer.valueOf(int) with new Integer(int)
McDowell
+3  A: 

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?

grom
By your definition, there is no pass by reference. Anything that is passed must have a value(even null is a value), even if it is just a value of the pointer, otherwise it is just an empty set. By CS terms, pass by reference is passing the value of the the reference(pointer). I'm a little confused.?
WolfmanDragon
A: 

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

Telcontar
+1  A: 

just as an additional comment: In a business application I would generally suggest to use not the primitive types but the Object versions. The simple reason for this is, that in most situations you have a underlying database, and in those cases the column my contain NULL, you get null in your object as well (for instance if you are using an orm like hibernate).

Mauli
+1  A: 

In platforms like java ints are primitives whilst Integer is an object which holds a int 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.

mP