• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

switch construct

 
Amit Kumar Ch
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
The following peice of code is from the K & B book.

1 final int a=1;
2 final int b;
3 b=2;
4 int x=0;
5 switch(x)
6 {
7 case a: //This line compiles fine.
8 case b: // This line gives a compiler error.


can anyone please tell me why line 8 gives an error?
 
Nilesh Raje
Ranch Hand
Posts: 153
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Amit,

What I think in this case is you need to intialize the final variable b in the declaration line itself.


You need to intialize the final variable where you have declared it.


1 final int a=1;
2 final int b;
3 b=2;
4 int x=0;
5 switch(x)
6 {
7 case a: //This line compiles fine.
8 case b: // This line gives a compiler error.
 
swanand paranjape
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
case expressions must be constant expressions , and in given code b is blank final variable , sa at compile time compiler checks the constant expression for case statement,
and b get value 2 at run time


please correct if any thing is wrong

swanand
 
Georgy Bolyuba
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Amit Kumar Ch:

1 final int a=1;
2 final int b;
3 b=2;


There is a difference between 'a' and 'b'. 'a' is initialized with a compile-time constant expression and is final. So we call it 'a constant variable'. 'b' is final but it is blank final variable. A blank final is a final variable whose declaration lacks an initializer.

That's why you cannot use 'b' in the way you are trying to use it.
 
A Kumar
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

We are assigning value to b...and final means once u assign a value ...we cannot change it...

So b does have a value...if a is initiliased with a value so does b holds a value..but after a step later...

Also suppose we pass a value to a function whose parameter is final ..then how does ..the function doesnt give any compiler error?

Tx
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic