Is that possible to apply increment using a ternary operator in Java?
For example I want to make this without an "if" statement, not because it will more readable or shorter, just I want to know.
if(recordExists(recordId)){
numberofRecords++;
}
Java ternary operator is the only conditional operator that takes three operands. It’s a one-liner replacement for if-then-else statement and used a lot in Java programming. We can use the ternary operator in place of if-else conditions or even switch conditions using nested ternary operators.
The meaning of ternary is composed of three parts. The ternary operator (? :) consists of three operands. It is used to evaluate Boolean expressions. The operator decides which value will be assigned to the variable. It is the only conditional operator that accepts three operands. It can be used instead of the if-else statement.
Nested Ternary Operator Example You can also use Ternary operated as nested conditions. For the example, if we compare for greatest value among three integer variables. Then if-else statement will be something like below.
In this tutorial, we are going to see one of the most used and confused operators in java. That is increment and decrement operators. Increment and decrement operators are unary operators.
Is that possible to apply increment using a ternary operator in Java?
You can use addition instead.
numberOfRecords += recordExists(recordId) ? 1 : 0;
IMHO This doesn't have side effects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With