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
posted
0
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
posted
0
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
posted
0
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....