Thursday, August 14, 2008

Java You Weirdo!

The following Java is legal. What does it even mean?


public class WeirdAssign {
static int foo() {
int a = a = 1; //Strange line
return a;
}
public static void main(String[] args) {
System.out.println("a is: " + foo());
}
}


The output of this test is, "A is: 1".

4 comments:

  1. Yeah, my thoughts exactly. On the scope issue. On the output issue, well my copying and pasting technique consists of me re-typing things I want to copy.

    ReplyDelete
  2. The brain painz....

    ReplyDelete
  3. Because of Java's "Definite Assignment" rules, it would make me upset if this weren't an error. Fortunately,

    int b = b;

    gives,

    WeirdAssign.java:3: variable b might not have been initialized.
    Actually, one of the most interesting things about the first 'weird assignment' is that Eclipse gives me a warning that it, "has no effect." That's the reason I noticed this whole thing in the first place. Eclipse caught a coding mistake that I made. javac gives no such warning though.

    ReplyDelete