File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Switch Statement

 
Hemant Gupt
Greenhorn
Posts: 26
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 74
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
the default statement is checked in the end, irrespective of where you put it in the switch. Thus, the answer is ten.
 
Hemant Gupt
Greenhorn
Posts: 26
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Hemant Gupt
Greenhorn
Posts: 26
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The questions is from the book Kathy Sierra
Page : 330
 
Prasad Shindikar
Ranch Hand
Posts: 114
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic