This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Switch Statement Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Switch Statement" Watch "Switch Statement" New topic

Switch Statement

Hemant Gupt

Joined: May 12, 2008
Posts: 26
public class MySwitch{
public static void main(String argv[]){
MySwitch ms= new MySwitch();
public void amethod(){
char k=10;
System.out.println("This is the default output");
case 10:
case 20:
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.

Minu Jain
Ranch Hand

Joined: Mar 24, 2008
Posts: 74
the default statement is checked in the end, irrespective of where you put it in the switch. Thus, the answer is ten.

"Even if you're on the right track, you'll get run over if you just sit there."
Hemant Gupt

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

This is contradicting the previous example. Please comment.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 13883

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

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.
I agree. Here's the link:
subject: Switch Statement
Similar Threads
Help with a question from JCHQ
default statement
switch() flow of execution
questions from Marcus Green tutorial
break in switch