| Author |
The Quickest of Questions about constants
|
Jose Campana
Ranch Hand
Joined: May 28, 2007
Posts: 339
|
|
Howdi there Java Master-minds ! I'm in the need to ask a simple question, but before, -a Disclaimer: I know there's a lot floating around the internet about "compile-time constants", But sometimes I have felt that too much Theory just contributes to shadow the practical knowledge. And well, given that statement above, here goes my question. I hope you guys can help me. For a variable to be used in a switch's case, Does it have to be marked final AND initialized to something? as in Am I correct in saying that it's just about those 2 conditions that must happen simultaneously, for it to be a Compile-time constant? Good Luck, your friend, Jose
|
 |
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
|
|
[Jose]: For a variable to be used in a switch's case, Does it have to be marked final AND initialized to something? as in Yes, unless the variable is an enum value. [Jose]: Am I correct in saying that it's just about those 2 conditions that must happen simultaneously, for it to be a Compile-time constant? No. It's also necessary that (a) the variable be a primitive type or String, and (b) the variable must be initialized with a compile-time constant expression. So is not a compile-time constant. [ December 22, 2007: Message edited by: Jim Yingst ]
|
"I'm not back." - Bill Harding, Twister
|
 |
Jose Campana
Ranch Hand
Joined: May 28, 2007
Posts: 339
|
|
Hello Mr Jim, Excuse my ignorance, Would a compile-time constant expression be any value assigned to a primitive or String variable that isn't calculated at Runtime? Am I correct? Best Regards, Jose
|
 |
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
|
|
[Jose]: Would a compile-time constant expression be any value assigned to a primitive or String variable that isn't calculated at Runtime? Almost. The only exception I can think of is null - which is a value that can be determined at compile time, but isn't considered a compile-time constant expression. In any event, I'm not sure how useful this rule is, since then you need to know: which types of expressions are calculated during runtime, and which at compile time? I recommend studying the rules in JLS 15.28 for further details.
|
 |
Jose Campana
Ranch Hand
Joined: May 28, 2007
Posts: 339
|
|
Hiya, Sure, I'll take a look at it. thanks for the replies. As always, If there's any further comments please let me know. Good Luck, Jose
|
 |
 |
|
|
subject: The Quickest of Questions about constants
|
|
|