• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

compile time constant expressions

 
cyril vidal
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:

but

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

but


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?
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah, it looks like you've got it down pretty well. As far as the intern method goes, I don't believe that will be on the exam.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic