Dear all, Is the following knowledge about compile time constants correct? 1�) A compile time constant is a literal (String or primtive type) declared with modifer final. Examples: final byte b = 6; final String s = "abc"; Declaring a variable as final isn't sufficient to become a compile time constant. Hence, final byte b; b = 6; would'nt make b a compile time constant. 2�) The trick cases where is it useful to know that the variable is a compile time constant one: a) Assignement conversion:
b) String reference:
OUtput: false Explanation: (Dan's mock exam)
The expression (a+b) is evaluated at runtime and produces a new instance of a String Object. Even thought the expression (a+b) produces the same result each time it is evaluated, each evaluation of the expression produces a new instance of the String
Outputs: true Explanation: (Dan's mock exam)
The key to understanding this program is understanding the impact of declaring variables "a" and "b" with the "final" modifier. Since "a" and "b" are final, all of the String expressions become compile-time constant expressions that evaluate to "AB". As a result, all are represented by a single String Object at runtime. Therefore, the equality operator finds that the references are equal and returns the value true.
Are these cases the only ones concerning compile time constants or are there others to be known? Thanks in advance for your response, Cyril. PS: In Dan's mock exam, sometimes, method intern() from String class is used. Have we to learn about it for the exam?
SCJP 1.4, SCWCD, SCBCD, IBM XML, IBM Websphere 285, IBM Websphere 287