JAVA short if else – ternary operator ?:

Java has a shortened version of an if else command. The use of it is very easy, if you understand it once.

It’s written:

x ? y : z;

Here the question mark and the colon will take the place of the commands if and else.
This means:

condition ? inCaseOfTrue : elseCase;

If the condition is true the part behind the questions mark will be taken, else the part behind the colon.
This shortened version has big advantages for coding, because it prevents blowing up your code.
e.g. if you want to return a string in a method depending on a parameter:

classic „version“, which is even short, just using the direct return.

public String getMood(boolean hasGoodMood){
        return "happy";
    return "sad";

And here the real short and smooth verion:

public String getMood(boolean hasGoodMood){
    return hasGoodMood ? "happy" : "sad";

Especially for setting strings the short if else show their potential, e.g.:

longString = longString.length()>5 ? longString.substring(0, 5) : longString;

This short line will substring a string and prevents an indexOutBounds in case that the string is not long enough.

At the end both (short and classic if else) will be compiled to the same, but the meaningful use will prevent blowing up your source code and keep it more structured.

Schreibe einen Kommentar

Ich akzeptiere