File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Autoboxing - Good or Bad Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Autoboxing - Good or Bad" Watch "Autoboxing - Good or Bad" New topic
Author

Autoboxing - Good or Bad

Anselm Paulinus
Ranch Hand

Joined: Sep 05, 2003
Posts: 389
I am wondering if the new feature in Java 1.5 - autoboxing; is it a good or bad feature? Personally, I feel it is going to make the understanding of Java more complex for beginners who would not know when to use primitives and when to use the object equivalent; since to them either will automatically convert based on which the compiler needs at any time. Also seasoned programmers might mistakenly use object in place of primitive thereby making their program less elegant due to the implicit conversion that has been built into the JVM.
Herb Schildt
Author
Ranch Hand

Joined: Oct 01, 2003
Posts: 239
In general, I think that autoboxing is good. It streamlines the coding of a very common situation. However, the main reason that autoboxing is important is that it makes generic code able to work seamlessly with primitive values. Here's how.

A generic type argument must be a reference type, not a primitive type. For example, given

class Gen<T>

you can declare

Gen<Integer> ob; // OK

but not

Gen<int> ob; // wrong


Now, assume that Gen has the following method:

T setVal(T v) { // ... }

Then, given this sequence:

Gen<Integer> ob = new Gen<Integer>();
ob.setVal(10); // OK because of autoboxing

Here, ob is a Gen<Integer> object, which means that T is replaced by Integer. In the second line, even though setVal() is expecting an Integer, it can be passed a primitive int (10 in this case) because that int is autoboxed into an Integer. In other words, the value 10 is automatically boxed into an Integer before being passed to setVal(). This results in the seamless integration of primitive types with a generic class and method.

Without autoboxing, the sequence would have looked like this:

Gen<Integer> ob = new Gen<Integer>();
ob.setVal(new Integer(10)); // old-style

In this case, the value 10 was manually wrapped in an Integer. This is not wrong. It's just that you no longer need to do this manually, which helps prevent accidental type mismatches, etc.

The reverse happens during auto-unboxing. An object of a primitive type wrapper is automatically unboxed into its primitive type. (For example, Integer into int.) Again, heading off errors and streamlining the integration of generic code with primitives.

The combination of autoboxing/unboxing is especially helpful when working with the Collections Framework because it enables primitive values to be easily stored in a collection, such as an ArrayList.


For my latest books on Java, including my Java Programming Cookbook, see HerbSchildt.com
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9048
    
  10
On the other hand, I find beginning Java programmers creating lots of unnecessary objects because they don't realize that they are automagically being created.


JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Herb Schildt
Author
Ranch Hand

Joined: Oct 01, 2003
Posts: 239
Marilyn,

True. However, autoboxing is here to stay. It does mean, of course, that it is very important to explain the implications and effects of autoboxing to beginners so that they avoid the situation that you describe. For example, here is one of the warnings that I give in my book:


Now that Java includes autoboxing and auto-unboxing, one might be tempted to use objects such as Integer or Double exclusively, abandoning primitives altogether. For example, with autoboxing/unboxing it is possible to write code like this.

In this example, objects of type Double hold values that are used to calculate the hypotenuse of a right triangle. Although this code is technically correct and does, in fact, work properly, it is a very bad use of autoboxing/unboxing. It is far less efficient than the equivalent code written using the primitive type double. The reason is that each autobox and auto-unbox adds overhead that is not present if the primitive type is used.

In general, you should restrict your use of the type wrappers to only those cases in which an object representation of a primitive type is required. Autoboxing/unboxing was not added to Java as a "back door" way of eliminating the primitive types.


In general, autoboxing is just one of many features which can be used or abused. Part of becoming a professional programmer is knowing how to use the feature wisely.
Anselm Paulinus
Ranch Hand

Joined: Sep 05, 2003
Posts: 389
Originally posted by Herb Schildt:
In general, I think that autoboxing is good. It streamlines the coding of a very common situation. However, the main reason that autoboxing is important is that it makes generic code able to work seamlessly with primitive values.



Hi Herb:

You did not mention the effect this has on new java programmers comprehending the new feature; knowing to use primitive in place of objects and vice-versa. I have been in project where new programmer use Boolean in place of boolean; this was caught due to the error that was generated later on. With unboxing, this would have easily sailed through without being noticed. What is your thought on this.
Anselm Paulinus
Ranch Hand

Joined: Sep 05, 2003
Posts: 389
Originally posted by Anselm Paulinus:



Hi Herb:

You did not mention the effect this has on new java programmers comprehending the new feature; knowing to use primitive in place of objects and vice-versa. I have been in project where new programmer use Boolean in place of boolean; this was caught due to the error that was generated later on. With unboxing, this would have easily sailed through without being noticed. What is your thought on this.


I made this post at same time you were responding to Marilyn.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[MdQ]: On the other hand, I find beginning Java programmers creating lots of unnecessary objects because they don't realize that they are automagically being created.

I wonder how much this really matters though. Nowadays the JMV is pretty well-optimized to garbage collect short-lifetime objects very quickly. I suspect that all these little objects being created automagically just aren't a significant problem in most cases. (Like most permormance optimizations, really.) There are probably some exceptions to this, and I'll be interested to find out just what they are.


"I'm not back." - Bill Harding, Twister
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30789
    
157

I think the extra complexity from autoboxing is more than made up for with the reduction in complexity for beginners. If a beginner mixes up primitives and objects at the beginning, it can become a design thing to learn later. Just like learning what kinds of loop to use in what case. It isn't wrong per se. Classcasts coming out of Lists, on the other hand, are harder to figure out.

New programmers also write

when starting out. It becomes a training issue to explain why they shouldn't. In my mind, double vs Double is quite similar to this.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Arjun K
Ranch Hand

Joined: Mar 09, 2005
Posts: 39
But there are some confusions:

Some thing like this
int single(int i){}
int single(Integer i){}

when U do a call as
single(100);/ Here it will calls <int single(int)> method
Integer ii = 100;
single(ii)// Then here it will call <int single(Integer)> method

Does it need to give a compile time error; on such confusion?

Regards,
Arjun
Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8919

Originally posted by Arjun kondepudi:
But there are some confusions:

Some thing like this
int single(int i){}
int single(Integer i){}

when U do a call as
single(100);/ Here it will calls <int single(int)> method
Integer ii = 100;
single(ii)// Then here it will call <int single(Integer)> method

Does it need to give a compile time error; on such confusion?

Regards,
Arjun



I dont see any need for it. The JLS clearly specifies how methods will be called and there is no confusion.


Groovy
Anselm Paulinus
Ranch Hand

Joined: Sep 05, 2003
Posts: 389
Originally posted by Pradeep Bhat:



I dont see any need for it. The JLS clearly specifies how methods will be called and there is no confusion.


There is definitely a confusion; do you know how many times programmers, even seasoned programmers have had to use String in place of StringBuffer even though the spec I guess specifies when to use what. Well that is programming anyway.
Like Herb stated in his book "Now that Java includes autoboxing and auto-unboxing, one might be tempted to use objects such as Integer or Double exclusively, abandoning primitives altogether." I think it is an extra layer of complexity new java programmers will have to deal with.
Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8919

here is definitely a confusion; do you know how many times programmers, even seasoned programmers have had to use String in place of StringBuffer even though the spec I guess specifies when to use what. Well that is programming anyway.


Where is it mentioned in JSL to use StringBuffer rather in String. Could you pass me the link/reference? Thanks
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Arjun kondepudi:
But there are some confusions:

Some thing like this
int single(int i){}
int single(Integer i){}

when U do a call as
single(100);/ Here it will calls <int single(int)> method
Integer ii = 100;
single(ii)// Then here it will call <int single(Integer)> method


If both methods do similar things, but optimized for the data type, it doesn't matter. If not, the confusion doesn't come from autoboxing, but from inappropriate use of method overloading, and can easily be recreated without autoboxing: just write a method single(Number).


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Autoboxing - Good or Bad