Page 1 of 1

About Question enthuware.ocajp.i.v7.2.1108 :

Posted: Thu Jul 11, 2013 5:57 am
by Rafael
What will the following program print?

class Test{    
public static void main(String args[]){       
int k = 9, s = 5;       
switch(k){          
default :          
if( k == 10) { s = s*2; }
         else{             s = s+4;
            break;          }         
 case 7 : s = s+3;       
}       
System.out.println(s);    
}
}
Possible answers: 5 - 9 - 12 - It won't compile.

The correct answer is 9, but I marked 12 because I thought keyword break finished 'else' block but not 'default' block. So, if I will write for example:

default:
if(true){
if(true){
if(true){
if(true){
s=0;
break; <- do this Break finish default case too?
}}}}
s=12345; <- is this Dead code?

Thank you so much¡ ;)

Re: About Question enthuware.ocajp.i.v7.2.1108 :

Posted: Thu Jul 11, 2013 6:24 am
by admin
1. Yes.
2. No, if(true) is a a special case that doesn't cause unreachable/dead code anywhere.

HTH,
Paul.

Re: About Question enthuware.ocajp.i.v7.2.1108 :

Posted: Fri Jul 13, 2018 9:54 am
by st.lisker
Hey! It's no break statement can be compiled in the else block!.. It must be fail to compile.

Re: About Question enthuware.ocajp.i.v7.2.1108 :

Posted: Fri Jul 13, 2018 8:49 pm
by admin
What happened when you actually tried to compile the given code? Observe that the break is inside the switch block.