Applying increment using ternary operator in Java

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.


Is that possible to apply increment using a ternary operator in Java?

Well you could write:

// Ick, ick, ick.
int ignored = recordExists() ? numberOfRecords++ : 0;

Or make a no-op method call:

// Ick, ick, ick.
Math.abs(recordExists() ? numberOfRecords++ : 0);

I would strongly discourage you from doing so though. It's an abuse of the conditional operator. Just use an if statement.

The purpose of a conditional operator is to create an expression whose value depends on a condition.

The purpose of an if statement is to execute some statement(s) based on a condition.

To quote from Eric Lippert's tangentially-related C# blog post:

The purpose of an expression is to compute a value, not to cause a side effect. The purpose of a statement is to cause a side effect.

EDIT: Given that doubt has been cast over the validity of this answer:

public class Test {
    public static void main(String[] args) {
        boolean condition = true;
        int count = 0;
        int ignored = condition ? count++ : 0;
        System.out.println("After first check: " + count);
        Math.abs(condition ? count++ : 0);
        System.out.println("After second check: " + count);
    }
}

Output:

After first check: 1
After second check: 2

Tags:

Java