Steffen Hvid
Steffen Hvid

Reputation: 187

Breaking out of an for statement in Java

If i do something like this

boolean ret;
for(int i = 2;i<30;i++) {
  if ( 30%i == 0){
    ret = true;
  } else {
    ret = false;
  }
}

ret becomes true allready at 2, but also at 5,10 15, is there anyway to break out of the for statement as soon as ret becomes true?

Upvotes: 0

Views: 56

Answers (3)

bowmore
bowmore

Reputation: 11280

Without using a structure breaking instruction, you can simply perform a check in the for condition.

boolean ret = false;
for(int i = 2;i<30 && !ret;i++) {
    if ( 30%i == 0){
        ret = true;
    } else {
        ret = false;
    }
}

Upvotes: 3

user173861
user173861

Reputation:

Have you considered the break command

boolean ret = false;
for(int i = 2; i < 30; i++){
    if(30%i == 0){
       ret = true;
       break;
    }
}

Upvotes: 3

Kilian Foth
Kilian Foth

Reputation: 14336

You can't break out of an if. By the time it has decided which way the condition goes, it's already over and there's nothing left to skip. You only can break out of a loop, like the for.

But the incomparably better way of exiting early is to put your sample code into a method and use return. More readable, and with a good method name the purpose of the entire code (and the return) is immediately clear.

Upvotes: 2

Related Questions