171

The keyword break in Java can be used for breaking out of a loop or switch statement. Is there anything which can be used to break from a method?

sashoalm
  • 75,001
  • 122
  • 434
  • 781
CodeMonkey
  • 2,511
  • 4
  • 27
  • 38
  • 2
    This question might also be worth checking: http://stackoverflow.com/q/18188123/2182237 – Don Aug 12 '13 at 20:03

7 Answers7

328

Use the return keyword to exit from a method.

public void someMethod() {
    //... a bunch of code ...
    if (someCondition()) {
        return;
    }
    //... otherwise do the following...
}

From the Java Tutorial that I linked to above:

Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this:

return;
Community
  • 1
  • 1
Mark Peters
  • 80,126
  • 17
  • 159
  • 190
  • Will this work for exiting from a constructor? I know it's a bit strange but I need this hack. – stillanoob Oct 21 '16 at 12:35
  • I am getting an error exiting the function with return type int[] using return; in if condition. Can you explain why? –  Oct 09 '21 at 07:25
  • @Vocado_xiix: this example is for returning from a `void` method. If your method needs to return a value, then it would be something like `return array;` where `array` is something you created in the method. – Mark Peters Oct 09 '21 at 15:01
  • @Vocado_ , There should be a return object (it could be `return null`) – smilyface Mar 10 '22 at 14:03
52

To add to the other answers, you can also exit a method by throwing an exception manually:

throw new Exception();

enter image description here

Jops
  • 22,535
  • 13
  • 46
  • 63
22

How to break out in java??

Ans: Best way: System.exit(0);

Java language provides three jump statemnts that allow you to interrupt the normal flow of program.

These include break , continue ,return ,labelled break statement for e.g

import java.util.Scanner;
class demo
{   
    public static void main(String args[])
    {
            outerLoop://Label
            for(int i=1;i<=10;i++)
            {
                    for(int j=1;j<=i;j++)
                    {   
                        for(int k=1;k<=j;k++)
                        {
                            System.out.print(k+"\t");
                            break outerLoop;
                        }
                     System.out.println();                  
                    }
             System.out.println();
            }
    }   
}

Output: 1

Now Note below Program:

import java.util.Scanner;
class demo
{   
    public static void main(String args[])
    {
            for(int i=1;i<=10;i++)
            {
                    for(int j=1;j<=i;j++)
                    {   
                        for(int k=1;k<=j;k++)
                        {
                            System.out.print(k+"\t");
                            break ;
                        }                   
                    }
             System.out.println();
            }
    }   
}

output:

1
11
111
1111

and so on upto

1111111111

Similarly you can use continue statement just replace break with continue in above example.

Things to Remember :

A case label cannot contain a runtime expressions involving variable or method calls

outerLoop:
Scanner s1=new Scanner(System.in);
int ans=s1.nextInt();
// Error s1 cannot be resolved
Lukas Knuth
  • 25,449
  • 15
  • 83
  • 111
Isabella Engineer
  • 3,733
  • 1
  • 15
  • 6
7

If you are deeply in recursion inside recursive method, throwing and catching exception may be an option.

Unlike Return that returns only one level up, exception would break out of recursive method as well into the code that initially called it, where it can be catched.

Audrius Meškauskas
  • 20,936
  • 12
  • 75
  • 93
3

use return to exit from a method.

 public void someMethod() {
        //... a bunch of code ...
        if (someCondition()) {
            return;
        }
        //... otherwise do the following...
    }

Here's another example

int price = quantity * 5;
        if (hasCream) {
            price=price + 1;
        }
        if (haschocolat) {
            price=price + 2;
        }
        return price;
kiyah
  • 1,502
  • 2
  • 18
  • 27
3

if (true) return; is the best solution that I use. you can use if(condition) testing that gives true or false.

Why?

  • using return; alone : gives Error:(105, 9) java: unreachable statement
public class Main
{
    public static void main(String[] args) {
        System.out.println("Hello World 1st code ");
        return;
        System.out.println("Hello World  2nd code ");
    }
}

Compilation failed due to following error(s).

Main.java:14: error: unreachable statement
        System.out.println("Hello World  2nd code ");
        ^
1 error

you can test it online using : https://www.onlinegdb.com/online_java_compiler

  • using exit(int status) example exit(0); : as you know terminate all the program (The java.lang.System.exit() method terminates the currently running Java Virtual Machine. See ref.) ; So exit , doesn't allow to break only the method and continue the execution of the caller

You can test the 3 techniques using the following code:

public class Main
{
    public static void do_something(int i)
    {
        System.out.println(" i : "+i);
        
        // break the method 
        /// System.exit(0); // stop all the program
        /// return;        // Main.java:20: error: unreachable statemen
        if(true) return;
        
        // do some computing 
        int res = i*i;
        
        System.out.println(" res : "+res);
        
    }
    public static void main(String[] args) {
        
        for (int i = 0; i <5; i++)
        {
            do_something(i);
        }
        
        System.out.println("Ouiiiii ,  work finished ");
    }
}

The result:

 i : 0                                                                                                                                          
 i : 1                                                                                                                                          
 i : 2                                                                                                                                          
 i : 3                                                                                                                                          
 i : 4                                                                                                                                          
Ouiiiii ,  work finished 
ibra
  • 1,164
  • 1
  • 11
  • 26
2

Use the return keyword to exit from a method.

public void someMethod() {
    //... a bunch of code ...
    if (someCondition()) {
        return;
    }
    //... otherwise do the following...
}

Pls note: We may use break statements which are used to break/exit only from a loop, and not the entire program.

To exit from program: System.exit() Method:
System.exit has status code, which tells about the termination, such as:
exit(0) : Indicates successful termination.
exit(1) or exit(-1) or any non-zero value – indicates unsuccessful termination.

Atharva
  • 41
  • 4