Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Default in Switch

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was expecting to see 'default', 100, 200 to be printed in this Class. But default does not print. Why??
New to the group and JAVA. Please comment:
public class SwitchTest {
public static void main(String args[]){
int test = 100;
switch(test){
case 20: System.out.println("20");
default: System.out.println("default");
case 100: System.out.println("100");
case 200: System.out.println("200"); //break;
}
}
}

 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kesava,
Welcome aboard, bring in your friends too
The position of the default does not matter in the case construct. It can appear anywhere among the different case options. It will only get executed when no case statements match. In your case 100 matched the value 100.
Also note that because none of your cases have break after the println, the control will "fall through". If you put default after 100, you will see default too.
Ajith
 
Ajay Kumar
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
If you put the case default: after the case 200: statement you will get the result you desire.
The way the switch statement works is once a matching case statement is found the execution starts at that statement and "falls through" the rest of the statements till a break is reached.
In you case it starts at case 100: and continues to case 200: before the conditional loop is exited.

public class SwitchTest {
public static void main(String args[]){
int test = 100;
switch(test){
case 20: System.out.println("20");
default: System.out.println("default");
case 100: System.out.println("100");
case 200: System.out.println("200"); //break;
}
}
}


Hope this helps.
------------------
Regds
Ajay Kumar
[This message has been edited by Ajay Kumar (edited June 02, 2000).]
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ajit,
Now I understand the rule. JLS do not discuss the placement of 'default'.
I got hooked on to this site. I am planning to take SCJP test next week. I am doing OK on Java Ranch. I have looked into 'java traps' and other mock tests. Please fill me in on any other resources that you can think of.
Thanks a lot for reply..
Kesava
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Did you look at www.javaranch.com/mock.html ??
Ajith
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic