Java Keywords (Part VIII): Skipping Loop Iterations and Escaping Loops

This should be a short one. This blog deals with the use of only two keywords: break and continue.

The Java keyword list has 24 keywords grayed out. That almost 50% of keywords covered by these series of articles. I suggest that if you have not read any of the articles in Java Keyword series, go back read them before proceeding further. Also, go back and read the one about Data Types. All of these articles are from September 2018. That should help you find them quickly. You can also use the "search" option at the top of this page.

Java keyword list

abstract continue for new switch
assert default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const* float native super while
Keyword marked with an asterisk (*) are keywords that, although valid, are not used by programmers.

Skipping a loop iteration

The keyword continue is used to skip a single iteration. This is very useful for cases when we are interested in something specific in the collection we are iterating over. A typical example used to illustrate its usage is a "search and replace" operation. For example, replace all instances of the letter "E" and replace them with the letter "A".

char[] myArr = {'C', 'E', 'N', 'E', 'D', 'E'};

for (int i=0; i < myArr.length; i++) {
  if ('E' != myArr[i]) {
    continue; // Don't do anything else. Just evaluate next character.
  }
  myArr[i] = 'A';
}

System.out.println(new String (myArr));
The code above should print out "CANADA." This example is trivial because after evaluating the current character in the array, only one line of code is skipped. However, if there were 19 other things to do after the evaluation, it would have skipped all the way to the end of the loop just the same, and it would have proceeded with the evaluation of the loop terminating condition and incremented the loop counter.

Terminating a loop early

Suppose you need to write a function that would look up a specific name in a list. Would it make sense to keep looking for a match after you found it? No, it doesn't make any sense to do so. Using the keyword break allows us to do just that.

In this example, we are iterating over a collection of phone book entries looking for a matching name. I will use the following classes to illustrate my example:


public class PhoneBookEntry {
    
    private String name;
    private String phoneNumber;

    // getter and setter methods omitted.
}
Suppose I create an array of entries containing the following data:

Name: Joe
Phone: 555-1234

Name: Jenny
Phone: 867-5309

Name: Carl
Phone: 555-9876

Name: Sue
Phone: 111-2222
If I were to look for Jenny's number in the entries array....

public String findPhoneNumberForName(String name, PhoneBookEntry[] entries) {

  String phoneNumber = "Not found.";

  for (int i = 0; i < entries.length; i++) {

    PhoneBookEntry entry = entries[i]; // get the next phone book entry
    String entryName = entry.getName();
    if (entryName.equals(name)) {
      phoneNumber = entry.getPhoneNumber();
      break; // found what we were looking for. Terminate the loop early.
    }
  }

  return phoneNumber;
}
Looping through the entries array will terminate after the second iteration.

And that concludes my blog on the topic of skipping iteration and terminating loops early using the Java keywords break and continue. The code below is the complete executable example.


public class PhoneBookEntry {

    private String name;
    private String phoneNumber;

    public String getName() {
        return name;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public static void main(String[] args) {
        PhoneBookEntry[] entries = new PhoneBookEntry[4];

        PhoneBookEntry joe = new PhoneBookEntry();
        joe.setName("Joe");
        joe.setPhoneNumber("555-1234");

        PhoneBookEntry carl = new PhoneBookEntry();
        carl.setName("Carl");
        carl.setPhoneNumber("555-9876");

        PhoneBookEntry sue = new PhoneBookEntry();
        sue.setName("Sue");
        sue.setPhoneNumber("111-2222");

        PhoneBookEntry jenny = new PhoneBookEntry();
        jenny.setName("Jenny");
        jenny.setPhoneNumber("867-5309");

        entries[0] = joe;
        entries[1] = jenny;
        entries[2] = carl;
        entries[3] = sue;

        String phoneNumber = findPhoneNumberForName("Jenny", entries);
        System.out.println(phoneNumber); // Prints out Jenny's number
    }

    public static String findPhoneNumberForName(String name, PhoneBookEntry[] entries) {

        String phoneNumber = "Not found.";

        for (int i = 0; i < entries.length; i++) {

            PhoneBookEntry entry = entries[i]; // get the next phone book entry
            String entryName = entry.getName();
            if (entryName.equals(name)) {
                phoneNumber = entry.getPhoneNumber();
                break; // found what we were looking for. Terminate the loop early.
            }
        }

        return phoneNumber;
    }
}

Next up, Part IX: Switch Statements

Comments

Popular posts from this blog

Implementing Interfaces with Java Records

Customizing Java Records

Exception Handling: File CRUD Operations Example