Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop executing further code in Java

Tags:

I have looked in the Javadoc but couldn't find information related to this.

I want the application to stop executing a method if code in that method tells it to do so.

If that sentence was confusing, here's what I want to do in my code:

public void onClick(){      if(condition == true){         stopMethod(); //madeup code     }     string.setText("This string should not change if condition = true"); } 

So if the boolean condition is true, the method onClick has to stop executing further code.

This is just an example. There are other ways for me to do what I am trying to accomplish in my application, but if this is possible, it would definitely help.

like image 421
Matt Smith Avatar asked Aug 04 '13 10:08

Matt Smith


People also ask

How do I stop a Java program execution?

In Java exit() method is in java. This System. exit() method terminates the current JVM running on the system which results in termination of code being executed currently. This method takes status code as an argument.

How do you break a flow in Java?

Java break statement As the name suggests, the break statement is used to break the current flow of the program and transfer the control to the next statement outside a loop or switch statement. However, it breaks only the inner loop in the case of the nested loop.

How do you stop a program if a condition is met Java?

As long as you are in the main() method of the program you can just call return to exit your program. In all other places you can exit the execution of your program using System. exit(1) with 1 replaced by the exit code you want to return.

Which Java statement is used to stop execution of program?

System. exit() method calls the exit method in class Runtime. It exits the current program by terminating Java Virtual Machine.


2 Answers

Just do:

public void onClick() {     if(condition == true) {         return;     }     string.setText("This string should not change if condition = true"); } 

It's redundant to write if(condition == true), just write if(condition) (This way, for example, you'll not write = by mistake).

like image 177
T_V Avatar answered Oct 13 '22 10:10

T_V


return to come out of the method execution, break to come out of a loop execution and continue to skip the rest of the current loop. In your case, just return, but if you are in a for loop, for example, do break to stop the loop or continue to skip to next step in the loop

like image 24
Jose Sutilo Avatar answered Oct 13 '22 08:10

Jose Sutilo