-4

I have a method with a break statement in its if statement. The method is in a while loop. Will it break out of the while loop if I use break within the method's if statement or do I have to use nested loops?

public int x=0;public int y=0;
public boolean endCondition = true;
public void someMethod()
{
  if(x!=y) {//do something}
  else break;
} 
while(endCondition==true)
{ 
  this.someMethod();
}
System.out.println("Bloke");
Community
  • 1
  • 1
gwrw
  • 139
  • 2
  • 12

3 Answers3

1

You can not use break without a loop or a switch . You need to use return. But it seems a endless method calling which would cause StackOverflow exception.

user207421
  • 305,947
  • 44
  • 307
  • 483
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
0

To break out from a function you have to use return. break will break you out from only the inner loop inside which you are calling it.

taufique
  • 2,701
  • 1
  • 26
  • 40
0

You probably need to return a boolean value from the method, which you can then use to decide whether to break the loop.

It's not important in this simple example, but it's usually a good idea to label your loops when using break, so it's clear what you are breaking out of, especially when using nested loops. See the label FOO below.

public boolean someMethod()
{
  if(x!=y) 
  {
    //do something
    return false;
  }
  return true; // break
} 

FOO:while(true)
{ 
  if(someMethod()) break FOO;
}
DNA
  • 42,007
  • 12
  • 107
  • 146