Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Switch statement

 
Kasak Tahilramani
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you use break and continue with labels in switch ?Because in Javabelt mock exams it says that you cannot use continue with labels in switch .
Please provide some example and solve this confusion .
 
Tommaso Nuccio
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

a switch statement is nothing else then
if()
else if()
else if()
else

Thus, labels with break and continue only make sense in loops, i.e. for, while.
 
Kasak Tahilramani
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But in exam cram book page 131 it says you can use labels with continue and break in switch.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If only there were some way that we could write programs ourselves to discover which of these statements is true.
 
Bert Bates
author
Sheriff
Posts: 8898
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If only there were some way that we could write programs ourselves to discover which of these statements is true.


 
Maneessh saxena
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi kasak,

See the code below……


class Code1{
public static void main (String[] args){
level1 :
for(int i=0 ; i <= 10 ;i++){
if(i == 9)continue level1;
System.out.println("Count is " + i);
}
}
}



class Code2{
public static void main (String[] args){
int i=0;
level1 :
for(; i <= 10 ;i++){
switch(i){
case 1 :
if(i == 9)continue level1;
System.out.println("Count is " + i);
default:
System.out.println("Default " + i);
break ;
}
}
}
}

We’ve got two forms of break & continue (one is labeled & another is unlabeled).We can use break in switch & in loop causes control coming out of current context.Whereas we can use continue in loops only whether they are labeled or unlabeled.
Try these codes …..
Hope this will help

Regards.....

Maneesh Saxena
 
Maneessh saxena
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by raunak saxena:
We can use break in switch & in loop causes control coming out of current context.
Hope this will help



In addition we can use labeled form of break also causes control coming out of label specfied....
 
Kasak Tahilramani
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot ranchers !
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic