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?
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;
To add to the other answers, you can also exit a method by throwing an exception manually:
throw new Exception();
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
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.
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;
来源:https://stackoverflow.com/questions/7937029/how-to-break-out-or-exit-a-method-in-java