Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying increment using ternary operator in Java

Tags:

java

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++;
}
like image 821
Spring Avatar asked Nov 02 '12 14:11

Spring


People also ask

What is ternary operator in Java?

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.

What is the meaning of ternary in JavaScript?

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.

What is an example of nested ternary operator in C?

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.

What are increment and decrement operators in Java?

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.


1 Answers

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.

like image 137
Peter Lawrey Avatar answered Sep 28 '22 01:09

Peter Lawrey