Difference between Return and Break statements

Java

Java Problem Overview


How does a return statement differ from break statement?.
If I have to exit an if condition, which one should I prefer, return or break?

Java Solutions


Solution 1 - Java

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).

So to answer your question (as others have noted in comments and answers) you cannot use either break nor return to escape an if-else-statement per se. They are used to escape other scopes.


Consider the following example. 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).
   ....
}

Solution 2 - Java

break is used when you want to exit from the loop, while return is used to go back to the step where it was called or to stop further execution.

Solution 3 - Java

You won't be able to exit only from an if condition using either return or break.

return is used when you need to return from a method after its execution is finished when you don't want to execute the rest of the method code. So if you use return, then you will not only return from your if condition, but also from the whole method.

Consider the following method:

public void myMethod()
{
    int i = 10;

    if(i==10)
        return;

    System.out.println("This will never be printed");
}

Here, using return causes to stop the execution of the whole method after line 3 and execution goes back to its caller.

break is used to break out from a loop or a switch statement. Consider this example -

int i;

for(int j=0; j<10; j++)
{
    for(i=0; i<10; i++)
    {
        if(i==0)
            break;        // This break will cause the loop (innermost) to stop just after one iteration;
    }

    if(j==0)
        break;    // and then this break will cause the outermost loop to stop.
}

switch(i)
{
    case 0: break;    // This break will cause execution to skip executing the second case statement

    case 1: System.out.println("This will also never be printed");
}

This type of break statement is known as unlabeled break statement. There is another form of break, which is called labeled break. Consider this example -

int[][] arrayOfInts = { { 32, 87, 3, 589 },
                            { 12, 1076, 2000, 8 },
                            { 622, 127, 77, 955 }
                          };
int searchfor = 12;

int i;
int j = 0;
boolean foundIt = false;

search:
    for (i = 0; i < arrayOfInts.length; i++)
    {
        for (j = 0; j < arrayOfInts[i].length; j++)
        {
            if (arrayOfInts[i][j] == searchfor)
            {
                foundIt = true;
                break search;
            }
        }
    }

This example uses nested for loops to search for a value in a two-dimensional array. When the value is found, a labeled break terminates the outer for loop (labeled "search").

You can learn more abour break and return statements from http://download.oracle.com/javase/tutorial/java/nutsandbolts/branch.html">`JavaDoc`</a>;.

Solution 4 - Java

No offence, but none of the other answers (so far) has it quite right.

break is used to immediately terminate a for loop, a while loop or a switch statement. You can not break from an if block.

return is used the terminate a method (and possibly return a value).

A return within any loop or block will of course also immediately terminate that loop/block.

Solution 5 - Java

Break statement will break the whole loop and execute the code after loop and Return will not execute the code after that return statement and execute the loop with next increment.

Break

for(int i=0;i<5;i++){
    print(i)
    if(i==2)
    {
      break;
    }
}

output: 0 1

return

for(int i=0;i<5;i++)
{
   print(i)
   if(i==2)
   {
    return;
   }
}

output: 0 1 3 4

Solution 6 - Java

break:- These transfer statement bypass the correct flow of execution to outside of the current loop by skipping on the remaining iteration

class test
{
    public static void main(String []args)
    {
        for(int i=0;i<10;i++)
        {
            if(i==5)
            break;
        }
        System.out.println(i);
    }
} 

output will be 
0
1
2
3
4

Continue :-These transfer Statement will bypass the flow of execution to starting point of the loop inorder to continue with next iteration by skipping all the remaining instructions .

class test
{
    public static void main(String []args)
    {
        for(int i=0;i<10;i++)
        {
            if(i==5)
            continue;
        }
        System.out.println(i);
    }
} 

output will be:
0
1
2
3
4
6
7
8
9 

return :- At any time in a method the return statement can be used to cause execution to branch back to the caller of the method. Thus, the return statement immediately terminates the method in which it is executed. The following example illustrates this point. Here, return causes execution to return to the Java run-time system, since it is the run-time system that calls main( ).

class test
{
    public static void main(String []args)
    {
        for(int i=0;i<10;i++)
        {
            if(i==5)
            return;
        }
        System.out.println(i)
    }
} 


output will be :
0
1
2
3
4

Solution 7 - Java

You use break to break out of a loop or a switch statement.

You use return in a function to return a value. Return statement ends the function and returns control to where the function was called.

Solution 8 - Java

break breaks the current loop and continues, while return it will break the current method and continues from where you called that method

Solution 9 - Java

Return will exit from the method, as others have already pointed out. If you need to skip just over some part of the method, you can use break, even without a loop:

label: if (some condition) {
    // some stuff...
    if (some other condition) break label;
    // more stuff...

}

Note, that this is usually not good style, though useful sometimes.

Solution 10 - Java

How does a return statement differ from break statement?. Return statement exits current method execution and returns value to calling method. Break is used to exit from any loop.

If I have to exit an if condition, which one should I prefer, return or break?

To exit from method execution use return. to exit from any loop you can use either break or return based on your requirement.

Solution 11 - Java

Break will only stop the loop while return inside a loop will stop the loop and return from the function.

Solution 12 - Java

break just breaks the loop & return gets control back to the caller method.

Solution 13 - Java

In this code i is iterated till 3 then the loop ends;

int function (void)
{
    for (int i=0; i<5; i++)
    {
      if (i == 3)
      {
         break;
      }
    }
}

In this code i is iterated till 3 but with an output;

int function (void)
{
    for (int i=0; i<5; i++)
    {
      if (i == 3)
      {
         return i;
      }
    }
}

Solution 14 - Java

If you want to exit from a simple if else statement but still stays within a particular context (not by returning to the calling context), you can just set the block condition to false:

if(condition){
//do stuff
   if(something happens)
        condition = false;
}

This will guarantee that there is no further execution, the way I think you want it..You can only use break in a loop or switch case

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndro SelvaView Question on Stackoverflow
Solution 1 - JavaAvada KedavraView Answer on Stackoverflow
Solution 2 - JavaOvais KhatriView Answer on Stackoverflow
Solution 3 - JavaMD Sayem AhmedView Answer on Stackoverflow
Solution 4 - JavaBohemianView Answer on Stackoverflow
Solution 5 - JavaR GView Answer on Stackoverflow
Solution 6 - JavaShubhendu PathakView Answer on Stackoverflow
Solution 7 - Javanana janashiaView Answer on Stackoverflow
Solution 8 - JavaEng.FouadView Answer on Stackoverflow
Solution 9 - JavaDirkView Answer on Stackoverflow
Solution 10 - JavaDcodeChefView Answer on Stackoverflow
Solution 11 - JavaImranul Hoque LimonView Answer on Stackoverflow
Solution 12 - JavaTechbrickView Answer on Stackoverflow
Solution 13 - JavaerdomesterView Answer on Stackoverflow
Solution 14 - JavaBenny TjiaView Answer on Stackoverflow