Stop executing further code in Java - java

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.

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

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

To stop executing java code just use this command:
System.exit(1);
After this command java stops immediately!
for example:
int i = 5;
if (i == 5) {
System.out.println("All is fine...java programm executes without problem");
} else {
System.out.println("ERROR occured :::: java programm has stopped!!!");
System.exit(1);
}

There are two way to stop current method/process :
Throwing Exception.
returnning the value even if it is void method.
Option : you can also kill the current thread to stop it.
For example :
public void onClick(){
if(condition == true){
return;
<or>
throw new YourException();
}
string.setText("This string should not change if condition = true");
}

You can just use return to end the method's execution

Either return; from the method early, or throw an exception.
There is no other way to prevent further code from being executed short of exiting the process completely.

I think just using return; would do the job

Related

How to stop execution of a method but continue the parent loop?

If the code faced a specific case I want to stop the current execution but continue the parent loop.
main() {
while(line not empty) {
// blablabla
method1()
// tadatadatada
}
}
method1() {
// blablabla
method2()
// etcetcetc
}
method2() {
// blablabla
if (var == 1)
stop the execution of the current method and parent method
// etcetcetc
}
In the case explained below, if var == 1, all etcetcetc part of code must not be executed, but tadatadatada must be...
So I want to stop all children executions.
Is there a solution to do that in Java?
Return a value from method2 and check it in method1. If it meets a condition, return from method1 too.
Something like:
method1() {
var shouldBreak = method2();
if (shouldBreak) {
return
}
// more stuff
}
Look into Java Multithreading. This will allow you to run multiple methods simultaneously and give you full control over when to stop a specific thread.
Here's a starting point from another: Threads in Java
I don't quite understand fully what you're asking as your example doesn't have extensive clarity, but hopefully this is what you're looking for.

Break while loop immediately when condition is false

Is there a possibility to break a while-loop immediately after the condition gets false?
while(true){
//Backgroundtask is handling appIsRunning boolean
while (appIsRunning) {
Roboter.movement1(); //while Roboter.movement1 is running appIsRunning changes to false
Roboter.movement2();
}
while (!appIsRunning) {
//wait for hardbutton/backgroundtask to set appIsRunning true
}
}
I don't want to wait until the first movement is done, the while should break immediatelty and closes the Roboter.class.
And I dont want to check inside the Roboter.class if appIsRunning is true...
If you want to completele stop Roboter.movement1() execution immideatly, you should use another thread and execute it there:
Thread mover = new Thread() {
#Override
public void run() {
Roboter.movement1();
}
}
mover.start();
and when you need to stop, use mover.stop();
Carefull: using stop() may cause wrong behaviour of your program
How do you kill a thread in Java?
Cleanest way to do it without re-thinking your "architecture" (which I would suggest, but depends on what you're trying to achieve would be to do:
while(true){
while (appIsRunning) {
if(!Roboter.movement1()) { //Hardbutton is pressed to stop application / appIsRunning is false
break;
}
Roboter.movement2();
}
while (!appIsRunning) {
//wait for hardbutton/backgroundtask to set appIsRunning true
}
}
And returning false from "movement1()" when you want to leave...
type break; where the condition fails! simple!

Turn the main into a thread

I created a program that runs in a sort of loop, and it stops only if a particular event happens; i forgot to implement the possibility to interrupt the program from "outside", for example typing "halt" in the prompt.
So now i have something like this:
public void main(....) {
instruction1;
instruction2;
while(true) {
if(???)
break;
}
}
And want change it in something like:
main() {
do {
instruction1;
instruction2;
...
...
} while(prompt do not contains 'halt');
I don't think that you want to turn main into a thread, try something like
while(true){
if(inputScanner.hasNext() && inputScanner.next().equals("halt")){
break;
}
/* Do whatever is needed */
}
What happens is that the scanner is checked for input without blocking the loop with the hasNext() method, and then only when it does have data to read in does it read the data in.

Stop current running thread with certain condition, with finally block being called

I have a method which is long and has many inner loops, at some point in the inner loop if a certain condition is met, I want the thread to be terminated but I also want the finally block to be called so clean up also happens. How can I do this?
Call return; when you want to stop. That will leave the loop and run the finally (so long as the loop with the return statement is within the try block).
E.g.
pseudocode:
public void run () {
try {
loop {
loop {
if (condition) return;
}
}
} finally {
// always run
}
}
Remember that "terminating the thread" really just means-- or should mean!-- that the run() method exits. Put the finally outside the loop, as the last thing in the thread's/Runnable's run() method.

Why am I get a warning "Dead code"?

if (myCondition1 && myCondition2 && myCondition3)
{
...
}
I wrote this code and run successfully. but I got warning about part of (...). The warning is "Dead code". It is just interesting to me. Do u have any idea?
thank u
"Dead code" is code that will never be executed. Most likely one of your conditions is hard-coded to false somewhere, making the conditional inside the if always false.
Dead code means it is never going to execute. E.g.
void someMethod() {
System.out.println("Some text");
return;
System.out.println("Another Some text"); // this is dead code, because this will never be printed
}
Same in case of your condition checking e.g.
String obj = "";
if(obj == null && obj.equals("")) { // here you get warning for Dead code because obj is not null and first condition is false so obj.equals("") will never evaluate
}
Your code inside the block is never reached. The reason is most likely that one of the conditions is always false.
If one or more of myCondition1, myCondition2 and myCondition3 are always false (like private const bool myCondition1 = false;) then that code inside the if will never be executed.
This could occur for a number of reasons. Either the whole of the if block is dead, caused by something like the following:
boolean condition1 = true;
boolean condition 2 = !condition1;
if(condition1 && condition2) {
//This code is all dead
Foo f = fooFactory();
f.barr(new Bazz());
}
Or you unconditionally leave the if block using something like return, break or continue, as shown below:
for(Foo f : foos) {
if(true) {
f.barr(new Bazz());
break;
//Everything after here is dead
System.out.println("O noes. I won't get printed :(");
}
}

Categories