Meaningless Drivel is fun!
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "a query about switch" Watch "a query about switch" New topic

a query about switch

Vishram Khare

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;

int x=0;
case a:
case b:


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.

Jiri Goddard

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
I agree. Here's the link:
subject: a query about switch
It's not a secret anymore!