aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes case doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "case doubt" Watch "case doubt" New topic
Author

case doubt

Pedro Ivo Dantas
Greenhorn

Joined: Sep 03, 2004
Posts: 10
Guys (and girls ;-))

I am reading the Bathy and Berts book and have a doubt about the case construct. Yhe book says "The case argument has to be resolved at compile time, so that means you can use only a constant or final variable that is assigned a literal value." It also has an example:

Ok, my doubt is: why do we get a compiler error when using variable b? I mean, it's declared final, and is assigned a value before the case test. So, in my opinion, it can be considered a constant, but Kathy (and the compiler, by the way) tell me otherwise. Could someone please explain this to me?
Thanks!
Pedro Ivo Dantas
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
This gets into the question of what the compiler knows and when it knows it.
"a" is essentially a synonym for 1 and is shown that way in the compiler's symbol table. You can use "a" pretty much any place you can use 1.

"b" is shown in the symbol table as a blank final variable. The rules are that it cannot be referenced until it is assigned a value (as usual) and that it can't be assigned a value after it has already been assigned a value. So "final int b;" and "b = 2;" are separate statements and "b" is not just a synonym for 2. Therefore, b can't be used after case.

Later in the compile process, the compiler will verify that b will always be assigned a value before it is used. Still later, an optimizing compiler may combine the "final int b;" and "b = 2;" statements for code generation purposes. However, for semantic analysis purposes, b has two possible values - unassigned and 2 - so it can't be used in place of 2 where only a constant will do;
[ November 03, 2004: Message edited by: Mike Gershman ]

Mike Gershman
SCJP 1.4, SCWCD in process
Pedro Ivo Dantas
Greenhorn

Joined: Sep 03, 2004
Posts: 10
Thaks fot the reply Mike!
Hai Le
Greenhorn

Joined: Sep 22, 2004
Posts: 28
thanx for both question and answer...!! it helps me pretty much to clear my head now...^_^


Step one step back to learn more thing..!!<br />Post to learn<br />learn from mistake<br />take whatever i understand...!!!<br /> <br />SCJP 1.4, Brainbench Java 1 & 2.<br />SCWCD 1.4 (preparing...!!)
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: case doubt