Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Final variables

 
Parinitha Paramesh
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 5905
63
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49432
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to the Ranch
 
Parinitha Paramesh
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Stephan van Hulst. Your answer really helped.
 
Parinitha Paramesh
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic