Thursday, September 15, 2005

Compile Time Constants - I


class FinalVarTest {

final int j = 55; // 1

// static final int j = 55; // 5

byte h = j; // 2

public static void main(String[] args) {

FinalVarTest nc = new FinalVarTest();

byte b1 = nc.j; // 3

}

}


why am I getting error in main method when I try to assign a compile time constant to a byte variable. I am doing the same at (2) for byte b where I am not getting any error.

Ans:

If you look at the JLS, at the definition for a compile time constant, you will find:

quote:

  • Simple names that refer to final variables whose initializers are constant expressions
  • Qualified names of the form "TypeName . Identifier" that refer to final variables whose initializers are constant expressions

first quote ==> final int j = 55;

second quote ==> FinalVarTest.j;

nc.j is not one of these types of names. j is a simple name, and if j was static, FinalVarTest.j would be.

nc.j is accessing j through a reference to an object. It's a qualified name, but not of the form required by JLS.

Here I've used j (simple name) and this.j (a qualified name - but not of the type required by JLS)

public void m() {

byte b1 = j;

// byte b2 = this.j; // this does not compile!

}




0 Comments:

Post a Comment

<< Home