aspose file tools*
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Switch Statement" Watch "Switch Statement" New topic
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
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14352
    
  22

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 8 API documentation
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Switch Statement