Page 1 of 1
About Question com.enthuware.ets.scjp.v6.2.257 :
Posted: Thu Dec 06, 2012 8:00 am
by ETS User
Can Switch block only contain final constants and integers? Can the case expression be a local variable?
Re: About Question com.enthuware.ets.scjp.v6.2.257 :
Posted: Thu Dec 06, 2012 1:02 pm
by admin
If you mean something like:
int x = 0;
int y = 1;
switch(x){
case y : do something; //this is invalid.
}
Then, no.
HTH,
Paul.
Re: About Question com.enthuware.ets.scjp.v6.2.257 :
Posted: Fri Dec 07, 2012 1:59 am
by Guest
Thank you. Yes, I was referring to that exact situation. I have come upon various ambiguous answers to the same.
Re: About Question com.enthuware.ets.scjp.v6.2.257 :
Posted: Thu Feb 05, 2015 11:57 pm
by faristhebest
for(;;)
{
Math.random()<.05? break : continue;
}
Sorry but who can explain me whats wrong here?? NOt short please if you can or links would be appreciated!
Re: About Question com.enthuware.ets.scjp.v6.2.257 :
Posted: Fri Feb 06, 2015 1:06 am
by admin
What did the compiler say when you tried to compile it?
Re: About Question com.enthuware.ets.scjp.v6.2.257 :
Posted: Thu May 14, 2015 3:28 pm
by pushpull
Can you tell me, why your answer has addition with such statement: "Even if break is inside the else block, it prevents the "fall through" to case 7." ? Because I tried a lot examples with switch, and this is just not true...
Re: About Question com.enthuware.ets.scjp.v6.2.257 :
Posted: Thu May 14, 2015 6:55 pm
by admin
Can you post the code that you tried? And did the control go into your else block?
Paul.
Re: About Question com.enthuware.ets.scjp.v6.2.257 :
Posted: Mon May 18, 2015 8:29 am
by pushpull
Code: Select all
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);
}
}
This is the code from the question. If you change the
to
it won't fall into the else and the break won't happen.
Re: About Question com.enthuware.ets.scjp.v6.2.257 :
Posted: Mon May 18, 2015 8:44 am
by admin
Ok, I see the confusion. The explanation that you've quoted is associated with that particular option. That is why it says, "....fall through to case 7". In the given situation, the control does go to else and it is trying to explain that it is not necessary for break statement to appear to be out of the if/else part. In the given code, even though the break statement is in the else part, it will still cause the case to break.
The statement that you've quoted is not a general rule that break in else will cause the case to break. Of course, the condition has to be false first so that the break is executed.
HTH,
Paul.