Forums Register Login

Default in Switch

+Pie Number of slices to send: Send
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;
}
}
}

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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).]
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
Did you look at www.javaranch.com/mock.html ??
Ajith
I will suppress my every urge. But not this shameless plug:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 838 times.
Similar Threads
What is this?
Need Help building Calculator
try/catch??
default statement
Selection Statements
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 01:24:37.