This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes a query about switch Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "a query about switch" Watch "a query about switch" New topic
Author

a query about switch

Vishram Khare
Greenhorn

Joined: Sep 23, 2007
Posts: 11
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

Joined: Aug 21, 2007
Posts: 21
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


http://dredwerkz.ic.cz
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: a query about switch
 
Similar Threads
The CASE of the STATIC initializer
Case constant must be compile time constant?
implicit casting of final variables
Switch Case constants
uninitialized final variable!