Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 207

Adding Optional Labels

Оглавление

One thing we intentionally skipped when we presented if statements, switch statements, and loops is that they can all have optional labels. A label is an optional pointer to the head of a statement that allows the application flow to jump to it or break from it. It is a single identifier that is followed by a colon (:). For example, we can add optional labels to one of the previous examples:

int[][] myComplexArray = {{5,2,1,3},{3,9,8,9},{5,7,12,7}}; OUTER_LOOP: for(int[] mySimpleArray : myComplexArray) { INNER_LOOP: for(int i=0; i<mySimpleArray.length; i++) { System.out.print(mySimpleArray[i]+"\t"); } System.out.println(); }

Labels follow the same rules for formatting as identifiers. For readability, they are commonly expressed using uppercase letters in snake_case with underscores between words. When dealing with only one loop, labels do not add any value, but as you learn in the next section, they are extremely useful in nested structures.

While this topic is not on the exam, it is possible to add optional labels to control and block statements. For example, the following is permitted by the compiler, albeit extremely uncommon:

int frog = 15; BAD_IDEA: if(frog>10) EVEN_WORSE_IDEA: { frog++; }

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

Подняться наверх