Menu
Coddy logo textTech

Label Statements

Part of the Logic & Flow section of Coddy's Java journey — lesson 35 of 59.

Label statements in Java allow you to mark specific points in your code and control the flow using break and continue statements with these labels. Labels are particularly useful when working with nested loops.

Create a nested loop with a label:

outer: for(int i = 0; i < 3; i++) {
   for(int j = 0; j < 3; j++) {
       if(i * j == 4) {
           break outer;
       }
   }
}

Use continue with a label:

firstLoop: for(int i = 0; i < 3; i++) {
   for(int j = 0; j < 3; j++) {
       if(j == 1) {
           continue firstLoop;
       }
       System.out.println(i + "," + j);
   }
}
challenge icon

Challenge

Easy

Create a method named findNumber that takes three arguments:

  1. A 2D array of integers (grid)
  2. An integer (target) to find
  3. A boolean (breakEarly) that determines if the search should stop after finding the first occurrence The method should use a labeled loop to search for the target number and print each position where it's found. If breakEarly is true, it should stop after finding the first occurrence. Each found element should be printed in the format: Found at: rowIndex,colIndex

Cheat sheet

Label statements in Java allow you to mark specific points in your code and control the flow using break and continue statements with these labels.

Create a nested loop with a label:

outer: for(int i = 0; i < 3; i++) {
   for(int j = 0; j < 3; j++) {
       if(i * j == 4) {
           break outer;
       }
   }
}

Use continue with a label:

firstLoop: for(int i = 0; i < 3; i++) {
   for(int j = 0; j < 3; j++) {
       if(j == 1) {
           continue firstLoop;
       }
       System.out.println(i + "," + j);
   }
}

Try it yourself

import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;

public class Main {
    public static void findNumber(int[][] grid, int target, boolean breakEarly) {
        // Write your code here
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // Read JSON string representing a 2D array
        String gridString = scanner.nextLine();
        // Read the target number
        int target = Integer.parseInt(scanner.nextLine());
        // Read the breakEarly flag
        boolean breakEarly = Boolean.parseBoolean(scanner.nextLine());
        
        Type gridType = new TypeToken<int[][]>(){}.getType();
        int[][] grid = new Gson().fromJson(gridString, gridType);
        
        findNumber(grid, target, breakEarly);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow