IntelliJ Java IDE
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes The Switch Statement Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "The Switch Statement" Watch "The Switch Statement" New topic
Author

The Switch Statement

Basu Patel
Ranch Hand

Joined: May 28, 2000
Posts: 60
Please refer to this program-
public class Agg{
static public int i=10;
public static void main(String argv[]){
switch(i){
default:
System.out.println("no value given");
case 1:
System.out.println("one");
case 10:
System.out.println("ten");
case 5:
System.out.println("five");
}
}
}
The ans. is-
ten
five
Can nay one tell me why five was also displayed considering i=10
is set on initialization, the switch statement should find the exact matching case right? Please help


<BR>Contact Me<BR> <A HREF="mailto:basu_patel@usa.net" rel="nofollow">basu_patel@usa.net</A> <P>
Tacha Arnull
Greenhorn

Joined: Aug 18, 2000
Posts: 12
The switch statement will look for a match and then execute all statements following that match until a break statement is encountered. i.e. if at the end of case 10: there was break; then the next case would not be executed
Sandeep Potnis
Ranch Hand

Joined: Aug 18, 2000
Posts: 39
You need to add a break statement at the end of every Case clause unless you want the subsequent case statements to be executed.
I've changed your code and pasted it below. Please try it out.

public class Agg{
static public int i=10;
public static void main(String argv[]){
switch(i){
default:
System.out.println("no value given");
case 1:
System.out.println("one");
case 10:
System.out.println("ten");
break;
case 5:
System.out.println("five");
}
}
}
Basu Patel
Ranch Hand

Joined: May 28, 2000
Posts: 60
Thanx Tacha and Sandeep for your time and efforts, How could i forget the braek command!
Basu
 
 
subject: The Switch Statement
 
Threads others viewed
default case in switch matches all the case
interesting code
Switch Statement
Question on switch construct
default statement
WebSphere development made easy
without the weight of IBM tools
http://www.myeclipseide.com