Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object or primitive type

Can someone explain to me the usage of Integer, Boolean etc in place of their primitive types in JAVA?

I can't seem to grasp the advantages their are providing. They seem to create unnecessary problems of handling null values.

Thanks!

like image 946
John Avatar asked May 21 '10 06:05

John


4 Answers

Boolean, Integer, Long, ... are Objects. You can use them in places where you can't use primitive types, e.g.

  • storing them in a Collection like a Map
  • using them as template parameter
  • assigning them a null value
  • using them in a more general way (e.g. Long as Number)

Examples:

new ArrayList<Integer>();
Long id = null;
Number num = new Long( 3 );
like image 70
tangens Avatar answered Dec 10 '22 19:12

tangens


The rationale for Integer, Boolean, and so on is to allow primitive types to be used in contexts that require a reference type. The classic use-case is the collection APIs which provide sets, lists, maps, queues and so on where the element type must be some reference type.

Thus I can write:

List<Integer> list = new ArrayList<Integer>();

but the following is a compilation error:

List<int> list = new ArrayList<int>();

Note that this use-case for the primitive wrapper types predates both generic types and the "new" collections APIs, and goes back to the days where the only collection types were the original (pre-generic) forms of Vector and Hashtable, and their ilk.

like image 31
Stephen C Avatar answered Dec 10 '22 21:12

Stephen C


Sometimes you really need a value to be nullable, for instance if your app stores user data, a social security # may be unknown. In that case it's cleaner to store null instead of -1.

Also there are things you can't do with primitive types, like storing them in a map or using polymorphism (Double and Integer both are instances of Number).

like image 20
Guillaume Avatar answered Dec 10 '22 19:12

Guillaume


primitives are always faster.
however there are times, when objects are really useful:
1. upcasting. Your function can take Number(is a parent for all numeric objects: Integer, Float, etc.) for an argument.
2. Possible null value. For example it is used while storing in database. Object can be null, primitives must have value. So if field in db is nullable, it is better to use object version of primitive value.
3. if function takes object and you always give it a primitive there are expenses on autoboxing(turning primitive into object). The same for returning from function.
4. Objects have certain methods, such as getHashcode(), toString() etc., which can be really useful in some cases.

like image 28
foret Avatar answered Dec 10 '22 21:12

foret