File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes help Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "help" Watch "help" New topic
Author

help

preety kumari
Greenhorn

Joined: Nov 03, 2000
Posts: 3
what is the output of the code?
char myChar = 'c';
switch(mychar) {
default:
case 'a' : System.out.println("I am in case a"); break;
case 'b' : System.out.println("I am in case b"); break;
}
The answer says "I am in case a"
but I think the output is nothing.
Can anyone clarify this, please.
Sudhir Bangera
Ranch Hand

Joined: Oct 10, 2000
Posts: 50
Hi Preety,
You are right, since 'c' is not found it goes to the default block, but notice that default is not the last statement and it does not have a break in it, so the next statement is displayed which is "I am in case a". If there was no break here too, then the statement "I am in case b" would be displayed too.
note: break is essential to get the correct desired output from a switch construct.
Hope this helps....
Harpal Singh
Ranch Hand

Joined: Oct 10, 2000
Posts: 229
preeti,
the problem is with your "default",it is in the wrong place....try commenting it or putting it in the last...it works....after default keyword it is taking the first case as default if the case does not match......
Harpal
preety kumari
Greenhorn

Joined: Nov 03, 2000
Posts: 3
thanks. I got your point.
Originally posted by Sudhir Bangera:
Hi Preety,
You are right, since 'c' is not found it goes to the default block, but notice that default is not the last statement and it does not have a break in it, so the next statement is displayed which is "I am in case a". If there was no break here too, then the statement "I am in case b" would be displayed too.
note: break is essential to get the correct desired output from a switch construct.
Hope this helps....

 
 
subject: help
 
Threads others viewed
Enum constants in Switch
default value for char?
Jqplus
SCJP question on loop
Cannot understand the output...
IntelliJ Java IDE