• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

SWITCH statement .

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Source : SCJP Java 2 by Kathy Sierra & Bert Bates.

import java.io.*;

public class Switch{


public static void main(String args[])
{
final int one =1 ;
final int two = 2 ;
int x = 1;
switch(x)
{
case one :

System.out.println("one");
break ;
case two :
System.out.println("two");
break ;
}
}

}

When I compiled the above program it compiled and executed correctly with an output one.

The above code uses final variables in a case statement . Note that if the final keyword is omitted , the above will not compile.


I understood that if we omit the final keyword , this will not compile but I did not understand why it compiled and executed properly if we add the final variable . Can anyone please explain it in detail ?

Thanks in advance .
[ September 11, 2007: Message edited by: Rakesh Yelugoila ]
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A switch label must represent a compile-time constant. If these variables were not final with their values known at compile time, then they could not be used as switch labels.
 
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Those are case constants. They can't be changed. By putting a variable there you have to use variables that are declared final. Anything goes there has to be some kinda of constants one way or other.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic