Java: bool + int

Viewed 102

Is there a way to make Java work with boolean/integer addition and evaluation? More specificly, C++ has an appropriate feature which shortens many if statements.

for (int i = 0; i < n; ++i)
    cout << i;

Is equivalent to

while (n--)
    cout << n;

Or, instead of:

for (int i = 0; i < n; ++i)
    if (x == y)
        count++;

One can have

for (int i = 0; i < n; ++i)
    count += (x==y);

Is there a way to do something similar to that in Java?

2 Answers

You can use ternary operator in Java for the same effect.

public class Main {
    public static void main(String[] args) {
        int x = 5, y = 10, count = 0;
        count += x == y ? 1 : 0;
        System.out.println(count);

        x = 10;
        count += x == y ? 1 : 0;
        System.out.println(count);
    }
}

Output:

0
1

Code is more often read than written. While you can use the ternary operator, the semantic of this boils down to only increasing count if x equals y. So the most readable way to write this would be to use:

for (int i = 0; i < n; ++i)
   if (x == y) count++;

Doing tricks like count += (x==y) in other languages is imho already bad practices since it obfuscates the logic. Optimize for reading, not writing.

Related