Sajad
Sajad

Reputation: 2363

Return statement function in if conodition

In my code:

if (id.isEmpty() || name.isEmpty()) {
    warlbl.setText("Warning, Empty ID or Name Fields");
    return;
}

id and name are String that give from JTextFields ,

Is necessary use return; in here or Not?

Upvotes: 0

Views: 111

Answers (2)

maxammann
maxammann

Reputation: 1048

return exits the current method you are "in".

Of yource it is not necessary but maybe you want to exit the method if id.isEmpty() and name.isEmpty(). So no and yes. It is not neccassary but you may want to return

You can use return to break out of a method, continue to skip a loop or a break to break out of a block.

Often there are 2 ways:

public void test() {
    if (!statement) {
       // to something if statement is false
    } else {
       //we failed, maybe print error 
    }
}

or:

public void test() {
    if (statement) {
       //we failed, maybe print error 
       return;
    }

    //do something if statment is false
}

But this is more a kind of "style". Mostly I prefere the second way, just because it's less spagetti :P

Keep in mind. If your return statement would be the last statment executed it's redundant.

Java reference:

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html

Upvotes: 1

arshajii
arshajii

Reputation: 129497

Yes, it can be:

if (...) {
    ...
    return;
}

// nothing at this point will be reached if the if-statement is entered

vs.

if (...) {
    ...
}

// code here will still be reached!

Upvotes: 4

Related Questions