• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

a query about switch

 
Vishram Khare
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everybody,

I am using the following code for demonstration of switch.(Reference K&B's book for SCJP 5.0 page 324)

public class SwitchDemo{
public static void main(String[] args){

final int a=10;
final int b;
b=2;

int x=0;
switch(x){
case a:
System.out.println("ABC");
break;
case b:
System.out.println("PQR");
break;
default:
System.out.println("XYZ");
break;
}

}
}

In this case,I am taking two final variables a & b.I assign the value 10 to the variable a right at the time of declaration.While in the case of variable b, I first declare it and then assign a value in the next line.

This program does not compile and the error I get is 'constant expression required'.

If I make slight change in the program and assign value 2 to the final variable b right at the time of declaration i.e. if I say final int b=2; and remove the line b=2, the program compiles and runs without any error or runtime exception.

In K&B's book it is written that case constants must be compile time constants.

The point I did not understand is what makes b a compile time constant if I assign value 2 to b right at the time of declaration? And what difference does it make if I first declare b to be an int type final variable and then assign value 2 to it? Afterall final variable is a final variable,whether we assign value right at the time of declaration or later on. Once a value is assigned to it,it cannot be changed.

So why does compiler complain in first case?

I would greatly appreciate help on this.

Thanks in advance.

----Girish
 
Jiri Goddard
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
basically it's because you could use later on the variable uninitialized in your program, which could cause a runtime error that's why you have to use the compile time constant. thanks for java safety
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic