Originally posted by Bill Shirley: You can't cast a primitive to an object.
Actually you can since Java 5 with autoboxing. For instance, the following is perfectly legal:
This is because 5 gets autoboxed to an Integer, which can be implicitly cast to Object without a problem. Of course there are limitations. For instance, widening then boxing won't work:
If you want to be specific (and verbose) about what you're doing:
will get done what you want.
I'd choose Short.valueOf instead of new Short, because it uses caching for all numbers between -128 and 127 (inclusive). The same applies to Byte, Integer and Long. [ October 09, 2008: Message edited by: Rob Prime ]
Joined: May 06, 2004
I think Bill meant that you can't explicitly cast from a primitive type to a reference type. In your examples, Rob, the change from primitive to object is always effected by means of an automatic boxing conversion, not an explicit cast like (Short)1.
What I wonder, nimo frey, is why you're using a Short in the first place. As a general rule, you should only use the primitive wrapper types (Short, Integer, Boolean, etc.) when you have to. Using primitives (short, int, boolean, etc.) whenever possible will tend to make your code more efficient, more readable, and less buggy. If you need to use the value in a place where an object is required, like storing it in a List, autoboxing will convert it for you at that time.