Unexpected Java Behaviour
By Zef Hemel
- 2 minutes read - 268 wordsWhen you dive real deep into a programming language, like “Martin Bravenboer”:http://mbravenboer.blogspot.com does, you’ll find some weird behaviour in there. Martin is posting a series of such unexpected behaviours in Java on his weblog.
For you to understand the part that I’m going to quote, you need to know what boxing is. If you know C#, you’re already familiar with it, boxing has been added to Java in version (1.)5.
In the pre-C#/Java5 age, you had typed arrays, like this:
int[] ar = new int[10 ];
However, if you wanted this array to expand and shrink as you added items to it, you needed to use an ArrayList or Vector:
ArrayList ar = new ArrayList();
This works fine as long as you put objects into such an ArrayList, putting primitive-type values in them — such as int, float, double, boolean and char — is a bit harder, as they’re not objects. The solution was to use an object wrapper:
ar.add(new Integer(5));
And to get it out:
int v = ((Integer)ar.get(0)).intVal();
Needless to say, this isn’t very convenient to the programmer. So, boxing was invented. Boxing is a feature that wraps and unwraps primitives automatically. If an object is wanted it boxes it, if a primitive is desired it unboxes it. Using this feature you can add and read primitive values like this:
ar.add(5); // box<br>int v = (int)ar.get(0); // unbox
OK, now you’re ready to read “Martin’s unexpected Java compiler behaviour tale”:http://mbravenboer.blogspot.com/2005/04/java-surprise-2-cast-priority.html:
public class JavaSurprise2 {<br> public static void main(String[] ps) {<br> int y = (int) - 2;<br> System.out.println(String.valueOf(y));<br> }<br>}
More is “here”:http://mbravenboer.blogspot.com/2005/04/java-surprise-2-cast-priority.html and an examplanation is “here”:http://mbravenboer.blogspot.com/2005/04/java-surprise-2-motivation.html.