user639285
user639285

Reputation: 55

java return in the if statement

How to use the return to retrieve a value out of an if statement? I don't want to return immediately, just like that:

if(){
return "something";
}

This isn't working for me, because if the return is successful the method returns, but I need to return it and when the return is complete to continue the actions in the method.

Upvotes: 0

Views: 116432

Answers (7)

Maxime Denuit
Maxime Denuit

Reputation: 41

This should be the easiest way in your case

return yourCondition ? "ifTrue" : "ifFalse";

Upvotes: 4

Preston
Preston

Reputation: 3271

Try something like:

String result = null;

if(/*your test*/) {

    result = "something";

}

return result;

Upvotes: 10

Andreas Dolk
Andreas Dolk

Reputation: 114767

If you want to "return" values from a method without actually returning from the message, then you have to define setter methods on the calling class and call them, like this:

public class Caller {

     private boolean someState;

     // ...

     public void doSomething() {
         // the method call
         Worker w = new Worker(this);
         int result = w.workForMe();
     }

     public void setState(boolean state) {
         this.someState = state;
     }

}

And the Worker

public class Worker {

    private Caller caller;

    public Worker(Caller caller) {
        this.caller = caller;
    }

    public int workForMe() {
        // now the conditions:
        if(clearBlueSky) {
            // this emulates a "return"
            caller.setState(true);
        }
        // this returns from the method
        return 1;
    }

}

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533492

Do you mean something like

String result = "unknown";
if(condition){
    result = "something";
}
// do something.
return result;

Upvotes: 0

jzd
jzd

Reputation: 23629

Use a finally block or save the return value in a variable that you return at the end of your code.

Upvotes: 0

Kal
Kal

Reputation: 24910

Store your string in a variable.

String s = null;
if( somecondition ) {
    s = "something";
}
// do other stuff
return s;

Upvotes: 2

Isaac Truett
Isaac Truett

Reputation: 8874

return is for methods. You probably want something like this:

int foo;

if (someCondition) {
    foo = 1;
} else {
    foo = 2;
}

Upvotes: 0

Related Questions