Tuesday, June 23, 2009

Case constants and compile time constants.

In Java, case constants in switch statements have to be compile time constants and ofcourse be byte, short, char, int or enum. Compile time constants' values are known at compile time. They are the static finals like 

static final int ME = 1;

static final byte BE = 1;

static final int US = ME*2;

whose values are known or can be computed at compile time. 


Not all static finals can be computed or known at compile time. For example the following cannot be computed at compile time:

static final int CURRENT_TIME = (int)System.currentTimeMillis()*24*60*60;

So it cannot be used as a case constant.


Now how about wrappers? Can the following be used as a case constant?

static final Integer CONSTANT = new Integer(1);

Wrappers are immutable and since it is declared as static final, the variable CONSTANT  is actually a constant, and since it can be auto unboxed, it can be used as a switch constant, right? Wrong! It turns out that it is not a compile time constant. Auto unboxing converts the Integer wrapper to a primitive int as follows:

CONSTANT.intValue(); 

So the value cannot be computed at compile time. In effect due to this conversion that needs to happen (eventhough it happens implicitly), wrappers cannot be compile time constants.

No comments:

Post a Comment