6

Possible Duplicate:
Why can Integer and int be used interchangably?

I am trying to understand the difference between these. Can I declare something to be an int for example and then compare this with a number that I put in an Integer? Also why does Java have the two. Why not just combine these?

Can someone help me by showing me a 3-4 line code example of how each is used?

Community
  • 1
  • 1
Alan2
  • 23,493
  • 79
  • 256
  • 450

6 Answers6

5

int primitive is not an object. Arrays allow primiteves:

int[] array = new int[10];

but generics don't:

List<int>  //won't compile

This is the primary reason to use wrapper classes these days. Also you can use Integer where Object is expected. Finally Integer can have null value if you want to implement optionality.

Note that there are some languages that dealt with that inconsistency. In you have value types, in Int class extend from AnyVal class while normal objects extend AnyRef (both of these extend from Any).

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
2

See boxing of types in Java. There is talk of making them exactly the same starting with Java 9.

pjulien
  • 1,369
  • 10
  • 14
2
  • Primitive int type and Integer class are different types. You can't compare directly a primitive int with a Integer object. You need to get intValue from the Integer object.
  • Yes, this is a required feature. Java and some other languages has these kinds of object wrappers for primitive types to handle the situations where an object is required. For example, a collection class will expect objects, you can't use primitive int with them. So you will need a Integer wrapper.
taskinoor
  • 45,586
  • 12
  • 116
  • 142
2

Integer is an object, whereas int is a primitive type. Fundamentally, objects are passed by reference, whereas primitives are passed by value. They also differ in where they are allocated from.

In terms of Java, an object has functions. Calling something like:

Integer.toString()

is fine, but:

int.toString()

is not.

Richard
  • 1,024
  • 1
  • 7
  • 15
  • Everything in java is pass by value. Both primitives and objects alike. Java happens to internally store objects as pointers, so the value of an object is a pointer. In fact, the java language spec specifically states that all method parameters are pass by value. However, people often mistake it for pass by reference because you can call a method that changes fields and the caller sees that. This has nothing to do with pass by reference. – Matt Jun 16 '12 at 17:57
1

int is a primitive, Integer is a class. You can't say ArrayList<int> but you can say ArrayList<Integer>.

Vincenzo Maggio
  • 3,787
  • 26
  • 42
1

All primitive types in Java have their class counterparts (classes descended from Object), for example Boolean, Long etc. It is called "boxing". Explanation see for example here.

comodoro
  • 1,489
  • 1
  • 19
  • 30