Stop a for loop in Java

How to stop a for loop in Java

Posted by Luke Beeno on September 5, 2022

Stop a for loop in Java

How to stop a for loop in Java

Posted by Luke Beeno on September 5, 2022

Here is how you can stop a for loop in Java.

Use the break keyword to stop a loop at a certain point. The break causes the code execution to exit the loop and start at the next statement in the program.

Here is an example below:

int[] arr = new int[]{1, 1, 3, 5, 5, 9, 2, 2, 2, 10};
int value = 0;
        
for (int i = 0; i < arr.length; i++) {
  if (arr[i] > 5) {
     value = arr[i];
     break;
  }
}
System.out.print(value);

The code execution went on to the next block of code once the if condition was true.