Skip to content
All Posts

Java Syntax and Runtime Error Notes

A diagnostic guide to Java enum switch labels, constant-expression requirements, and comparator contract violations.

an enum switch case label must be the unqualified name of an enumeration constant

private void Test(ColorType type){
switch (type){
case ColorType.GREEN:
break;
case ColorType.RED:
break;
case ColorType.ORANGE:
break;
default:
break;
}
}

Fix

A case label must contain only the enum constant, without the class qualifier. The switch expression already determines the enum type.

private void Test(ColorType type){
switch (type){
case GREEN:
break;
case RED:
break;
case ORANGE:
break;
default:
break;
}
}

constant expression required

private void Test(int type){
switch (type){
case ColorType.GREEN.getCode():
break;
case ColorType.RED.getCode():
break;
case ColorType.ORANGE.getCode():
break;
default:
break;
}
}

Fix

The result of an enum method is not a compile-time constant, while a case label requires one. Convert the integer to an enum value first, then switch on the enum.

Comparison method violates its general contract!

Since JDK 7, a Comparable implementation must satisfy reflexivity, symmetry, and transitivity. This error commonly occurs when symmetry is violated—for example, when the comparator never returns equality.

For compatibility with code written for JDK 6 or earlier, call:

System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");

Alternatively, pass -Djava.util.Arrays.useLegacyMergeSort=true to the JVM. JDK 7 and later use TimSort by default.


Originally published on SegmentFault.