| Author |
Switch Statement
|
Hemant Gupt
Greenhorn
Joined: May 12, 2008
Posts: 26
|
|
public class MySwitch{ public static void main(String argv[]){ MySwitch ms= new MySwitch(); ms.amethod(); } public void amethod(){ char k=10; switch(k){ default: System.out.println("This is the default output"); break; case 10: System.out.println("ten"); break; case 20: System.out.println("twenty"); break; } } } 1) None of these options 2) Compile time errror target of switch must be an integral type 3) Compile and run with output "This is the default output" 4) Compile and run with output "ten" Answer is 4. Please tell why it is not 3, but default statement also satisfy the condition. Regards, Hemant
|
 |
Minu Jain
Ranch Hand
Joined: Mar 24, 2008
Posts: 74
|
|
Hi the default statement is checked in the end, irrespective of where you put it in the switch. Thus, the answer is ten.
|
SCBCD5, SCWCD5, SCJP5
"Even if you're on the right track, you'll get run over if you just sit there."
|
 |
Hemant Gupt
Greenhorn
Joined: May 12, 2008
Posts: 26
|
|
As per Kathy Sierra, int x = 7; switch (x) { case 2: System.out.println("2"); default: System.out.println("default"); case 3: System.out.println("3"); case 4: System.out.println("4"); } Running the preceding code prints default 3 4 --------- This is contradicting the previous example. Please comment.
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12956
|
|
Hermant, when you copy a question from a book or mock exam, we require that you quote your sources. So, please tell us where you copied it from. Note that if you don't, I will have to delete your question.
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Hemant Gupt
Greenhorn
Joined: May 12, 2008
Posts: 26
|
|
The questions is from the book Kathy Sierra Page : 330
|
 |
Prasad Shindikar
Ranch Hand
Joined: Feb 18, 2007
Posts: 114
|
|
Please tell why it is not 3, but default statement also satisfy the condition. In the switch statement, if the match "10" would not have been found, only in that case, it would have printed the default value. Since the value 10 is found in the switch statement, the case matching the value is selected for further processing. Also notice the "break" at the end of all the case statements.
|
 |
 |
|
|
subject: Switch Statement
|
|
|