Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

if() condition exit

 
Vaibhav Goel
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello there,

We know that break keyword is used to come outside from a while condition. After break, loop terminates and control goes out of loop.
Same thing I want to do with if condition. In my if condition there are several other if contions with while loops as well.
At any certain point I want to come outside the main if block.
Please tell me how can I do so because we cannot use break inside if condition.
 
Kishore Kumar
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you can do it by using a Conditional break statement.
 
Kishore Kumar
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry it is not conditional break statement. it is a named break statement.
 
ahmed yehia
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can do it with a labeled break statement:

Prints: "A"
 
Kishore Kumar
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For example see the foloowing small code:
class BreakIF
{
public static void main(String[] args)
{
int i = 10;
FirstBreak:
if(i == 10){
int j = 2;
System.out.println("inside true part");
if(j == 2){
break FirstBreak;
}
while(j == 2){
System.out.println("inside while loop: " + j);

}
}else{
System.out.println("inside else statement");
}

}
}

While loop is an infinite loop, but while loop does not get executed because of early break of if condition. I think this will help you.
 
deepesh mathur
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i think there is one more solution
as an if method can be cared off when it's condition is false ..
look at code

if(SOP("hello")==0)
{
SOP("hello");
}
else
{
SOP("world");
}
//prints "hello world" get it..
so by using proper instance variable we can have if() loop terminated at right time..
(if not correct please let me know)
 
deepesh mathur
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i think there is one more solution
as an if method can be cared off when it's condition is false ..
look at code

if(SOP("hello")==0)
{
SOP("hello");
}
else
{
SOP("world");
}
//prints "hello world" get it..

so by using proper instance variable we can have if() loop terminated at right time..
(if not correct please let me know)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic