public class PrintWords {
public static void main(String[] args) {
System.out.println(Words.FIRST + "" + Words.SECOND + "" + Words.THIRD);
}
}
class Words {
// Compile PrintWords against this version public static final String FIRST="the";//the constant public static final String SECOND =null;//Not a constant! public static final String THIRD="set";//the constant}
class Words {// Run against this version public static final String FIRST="physics";
public static final String SECOND="chemistry";
public static final String THIRD="biology";
}
Output:
the chemistry set
What exactly is constant variable?
primitive and string constant variable whose value is compile time constant.
final string initialised to null is not a constant.
Not the Enums are not the constant expressions.
Solution
public static String ident(String s)
{
return s;
}
class Words {
// Compile PrintWords against this version public static final String FIRST=ident("the");//the constant public static final String SECOND =ident(null);//Not a constant! public static final String THIRD=ident("set");//the constant}
The Moral
- Constant variables are inlined
Only primitives and strings can be constant
null is not a constant
- If you change the value of a constant variable without recompiling its clients, their behaviorbecomes very confusing
- Use constant variables only for entities whose value will never change
-Use ident for final fields whose value may change
No comments:
Post a Comment