Unexpected Java Behaviour

When 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
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:

I'm going to abuse your familiarity with autoboxing to show how weird it can be that the priority of primitive casts is different from reference casts. The following program is a correct program that includes a (redundant) cast to an int.

public class JavaSurprise2 {
  public static void main(String[] ps) {
    int y = (int) - 2;
    System.out.println(String.valueOf(y));
  }
}

Compile and run:

martin@logistico:~/tmp> javac JavaSurprise2.java
martin@logistico:~/tmp> java JavaSurprise2
-2

Well, that looks great. Now, let's replace the int with an Integer.

public class JavaSurprise2 {
  public static void main(String[] ps) {
    int y = (Integer) - 2;
    System.out.println(String.valueOf(y));
  }
}

Compile ...

martin@logistico:~/tmp> javac JavaSurprise2.java
JavaSurprise2.java:4: cannot find symbol
symbol  : variable Integer
location: class JavaSurprise2
    int y = (Integer) - 2;
             ^
JavaSurprise2.java:4: illegal start of type
    int y = (Integer) - 2;
            ^
2 errors

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.