Avatar ·

How to exit nested loops in Java? Effective ways to break out

Hi everyone! I'm new to Java and encountered a problem when working with nested loops. I have a two-dimensional array (matrix) and I'm searching for a specific value in it. Once I find it, I need to stop the search and exit both loops. Here's my code: ```java int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int target = 5; boolean found = false; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { if (matrix[i][j] == target) { found = true; break; // exits only the inner loop } } // outer loop continues! } ``` I tried using `break` — but it only breaks the inner loop, while the outer loop continues iterating. Because of this, the code runs longer than