bem’s blog

 
« Back to blog

Fun with constants in Java

The following code does not compile:

public class A {
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
switch (i) {
case X: System.out.println("ONE!"); break;
case Y: System.out.println("TWO!"); break;
default: System.out.println("ZERO!"); break;
}
}
public static final int X = B.getNumber("X");
public static final int Y = B.getNumber("Y");
}

class B {
public static int getNumber(String s) {
if (s.equals("X")) {
return 1;
}
else if (s.equals("Y")) {
return 2;
}
else {
return 0;
}
}
}

The compile error is:

A.java:5: constant expression required
case X: System.out.println("ONE!"); break;
^
A.java:6: constant expression required
case Y: System.out.println("TWO!"); break;
^
2 errors

I think I'll leave explaining why as an exercise for the reader. (Or for a future post. ;-)

Comments (0)

Leave a comment...

 
To leave a comment on this posterous, please login by clicking one of the following.
Posterous-login     twitter