• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

a query about switch

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic