-1

Let's assume that we have a for-loop that will loop through a collection or array of Strings. In that case, I am searching for a specific keyword (ex. hey) here's how I usually achieve that:

for (String result : strings)
{
    if (result == "hey")
    {
        // Do something with that.
        break;
    }
}

Now, the question arises from that code snippet is, should I place a keyword (return or break) when the if-statement returns true so the loop will not continue? If not, what will happen and what's the correct way of going about it.

Edit: What happens when you use break and return? What's the difference?

Thanos Paravantis
  • 7,393
  • 3
  • 17
  • 24

2 Answers2

1

Let's put your code inside a method:

private void foo() 
{
    for (String result : strings)
    {
        if (result.equals("hey"))
        {
            // Do something with that.
            break;
        }
    }
    bar();
}

If you use break;, the loop will terminate and bar will be reached. If you use return, the method will terminate and bar won't be executed.

Note that comparing strings should be done using equals, == compares references and not content.

Maroun
  • 94,125
  • 30
  • 188
  • 241
0

If you know the word can only be found once you can surely place an break; statement so the loop won't continue after finding the match.

If you can have more than one match and you want the if block to be executed for each of those matches you should NOT put the break statement since it will stop the execution of the loop after the first match is found.

The Javatar
  • 695
  • 5
  • 15