This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
The moose likes Java in General and the fly likes Final variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Final variables" Watch "Final variables" New topic
Author

Final variables

Parinitha Paramesh
Greenhorn

Joined: Jan 21, 2013
Posts: 5
Hi,

I am a beginner to programming. I am currently preparing for SCJP 6 when I came across this code on final variables. Can anybody just help me out with this?

final int a = 1;
final int b;
b = 2;
int x = 0;
switch (x) {
case a: // OK
case b: // compiler error

When I tried this code, I got a compile error like this:

constant expression required for case b:

My doubt is if final variables can be initialized anytime(not necessarily at the time of the declaration of the variable), then why am I getting this error for variable b?
Thanks in advance.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 4088
    
  18

Because switch cases require constant expressions, and final variables are not constant expressions unless they are initialized in the same line they're declared. It's just a language rule.


The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 44525
    
  34
And welcome to the Ranch
Parinitha Paramesh
Greenhorn

Joined: Jan 21, 2013
Posts: 5
Thanks Stephan van Hulst. Your answer really helped.
Parinitha Paramesh
Greenhorn

Joined: Jan 21, 2013
Posts: 5
Thanks Campbell Ritchie. I'm hoping to get most of my doubts cleared through this portal as I'm a beginner to programming and I don't have much help around me to resolve my queries.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Final variables
 
It's not a secret anymore!