break vs return

break is used to exit (escape) the for-loop, while-loop, switch-statement that you are currently executing.
return will exit the entire method you are currently executing (and possibly return a value to the caller, optional).

you cannot use either break nor return to escape an if-else-statement. They are used to escape other scopes.

The value of x inside the while-loop will determine if the code below the loop will be executed or not:

void f()
{
   int x = -1;
   while(true)
   {
     if(x == 0)
        break;         // escape while() and jump to execute code after the the loop 
     else if(x == 1)
        return;        // will end the function f() immediately,
                       // no further code inside this method will be executed.

     do stuff and eventually set variable x to either 0 or 1
     ...
   }

   code that will be executed on break (but not with return).
   ....
}

break leaves a loop, continue jumps to the next iteration.

    class BreakContinue {
        public static void main( String [] args ) {
               for( int i = 0 ; i < 10 ; i++ ) {
                     if( i % 2 == 0) { // if pair, will jump
                         continue; // don't go to "System.out.print" below.
                     }
                     System.out.println("The number is " + i );

                     if( i == 7 ) {
                         break; // will end the execution, 8,9 wont be processed
                      }
               }
        }
    }

Ans
The number is 1
The number is 3
The number is 5
The number is 7

Leave a comment