Skip to main content

Understanding the Java Ternary Operator and Modulo Operator: Examples That Print Odd Numbers

The Java programming language provides several operators that can be used to perform arithmetic, comparison, and logical operations. In this blog post, we will discuss two of these operators: the ternary operator and the modulo operator. We will use these operators to write code examples that print odd numbers.

The Ternary Operator

The ternary operator is a shorthand way of writing an if-else statement in Java. It has the following syntax:

condition ? expression1 : expression2

The "condition" is evaluated, and if it is true, "expression1" is returned. If "condition" is false, "expression2" is returned. Here is an example of using the ternary operator to print odd numbers:

for (int i = 1; i <= 10; i++) {
  int result = i % 2 == 0 ? 0 : i;
  System.out.println(result);
}

In this example, the "condition" is "i % 2 == 0", which checks if "i" is even. If "i" is even, "expression1" is 0. If "i" is odd, "expression2" is "i". Therefore, the value of "result" will be 0 for even numbers and the value of "i" for odd numbers.

The Modulo Operator

The modulo operator, denoted by the "%" symbol, is used to find the remainder of a division operation. Here is an example of using the modulo operator to print odd numbers:

for (int i = 1; i <= 10; i++) {
  if (i % 2 != 0) {
    System.out.println(i);
  }
}

In this example, the "if" statement checks if "i" is odd by using the modulo operator to find the remainder of "i" divided by 2. If the remainder is not 0 (i.e., "i" is odd), the value of "i" is printed to the console.

Conclusion

The ternary operator and modulo operator are two useful tools in the Java programmer's toolbox. By using these operators to write code examples that print odd numbers, we have demonstrated their practical applications. We hope this blog post has been helpful in understanding the purpose and usage of the ternary and modulo operators in Java.

Happy coding!

Comments