DEV Community

Cover image for Enhance Your Java Code Effectiveness Using Ternary Operator
luthfisauqi17
luthfisauqi17

Posted on

Enhance Your Java Code Effectiveness Using Ternary Operator

In this article I will teach you how you can improve your Conditional Statement code using Ternary Operators. How do you usually code Conditional Statements? is it like the code below?

Source code 1:

public boolean isEvenNumber(int number) {
    if(number % 2 == 0) {
        return true;
    }
    else {
        return false;
    }
}
Enter fullscreen mode Exit fullscreen mode

If yes, then you can make it even better using the Ternary Operator as in Source code 2 below:

Source code 2:

public boolean isEvenNumber(int number) {
    return number % 2 == 0 ? true : false;
}
Enter fullscreen mode Exit fullscreen mode

The output results generated by Source code 1 and Source code 2 are completely the same. You can write code with the same results but with a much more effective number of lines of code using the Ternary Operator. How did this happen?


If we look at Source code 1 and Source code 2 carefully, then we will see a pattern that bridges the two Source codes. Let's break down the body Source code 2 method to see the pattern:

return number % 2 == 0 ? true : false;

From the code snippet above, we will be able to see the 3 main components that make up a ternary operator:

  • number % 2 == 0 is the condition.
  • ? true is the value that appears if the previous condition is met.
  • : false is the value that appears if the previous condition is not met.

How about return? return will return the value corresponding to the result of the ternary operation. The return here is actually optional because there is also a ternary operation without returning any value. We will see examples of other ternary operations in the following section.

As you can see, the pattern of the ternary operator is very similar to the if conditional statement, but the ternary operation is much shorter. My personal opinion is that the ternary operator is very similar to the concept of Value increment, in that you can shorten var = var + 1 to var++. So if the concept of value increment can be used to shorten the increment value operation, the ternary operator can be used to shorten the coding of conditional statements.


To better understand Ternary Operators, we will look at some examples of how they are implemented in coding.

Example 1

Suppose we will create a method to determine whether the input number that we input is an odd number or not. Implementation using normal conditional statements can be seen in Source code 3, and the implementation of the ternary operator can be seen in Source code 4.

Source code 3:

public boolean isOddNumber(int number) {
    if(number % 2 != 0) {
        return true;
    }
    else {
        return false;
    }
}
Enter fullscreen mode Exit fullscreen mode

Source code 4:

public boolean isOddNumber(int number) {
    return number % 2 != 0 ? true : false;
}
Enter fullscreen mode Exit fullscreen mode

Example 2:

Suppose we will create a method to normalize an input name, for example if the input name is null, then we will return the value "Stranger". Implementation using normal conditional statements can be seen in Source code 5, and the implementation of the ternary operator can be seen in Source code 6.

Source code 5:

public String normalizeName(String name) {
    if(name == null) {
        return "Stranger";  
    }
    else {
        return name;
    }
}
Enter fullscreen mode Exit fullscreen mode

Source code 6:

public String normalizeName(String name) {
    return name == null ? "Stranger" : name;
}
Enter fullscreen mode Exit fullscreen mode

Example 3:

Suppose we will create a method to display the number we input, but if the number we input is null, then we will display the text "Number input is null!". Implementation using normal conditional statements can be seen in Source code 7, and the implementation of the ternary operator can be seen in Source code 8.

Source code 7:

public void displayNumber(Integer number) {
    if(number == null) {
        System.out.println("Number input is null!");
    }
    else {
        System.out.println("Your number is " + number);
    }
}
Enter fullscreen mode Exit fullscreen mode

Source code 8:

public void displayNumber(Integer number) {
    System.out.println(number == null ? "Number input is null!" : "Your number is " + number);
}
Enter fullscreen mode Exit fullscreen mode

And that's how you make your code more effective using the ternary operator. Of course, the material that I cover in this article is still incomplete because the conditional statement that we change to a ternary operator only consists of if and else, what if there is an else if. Ternary operators that have an else if are usually referred to as "Chained Ternary Operators" or "Multiple Conditions Ternary Operators" which we will discuss in the next article.


Cover image: https://i.picsum.photos/id/882/1920/720.jpg?hmac=-m4frcxPW1QpFYu5cokcHkKkLgJMbq1kHk10I2dghcA

Top comments (2)

Collapse
 
cicirello profile image
Vincent A. Cicirello • Edited

Both versions of your isOddNumber and your isEvenNumber use bad style. Your other examples are fine. Here is the style problem with the those. In those examples, you are simply returning a boolean that directly corresponds to the condition you are evaluating. It is better style in a case like that to just use the expression without the if or ternary such as the following:

public boolean isOddNumber(int number) {
    return number % 2 != 0;
}

public boolean isEvenNumber(int number) {
    return number % 2 == 0;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
luthfisauqi17 profile image
luthfisauqi17

Exactly, thank you for pointing that out. In those cases, as you said, we don't actually need ternary operator. We can directly put the conditional checking result as the return value. Thank you for the correction.