Search code examples
javastringbuilderternary-operator

Java ternary operator not working?


Let's assume we have an StringBuilder and an double. Now want to append the double. If the double can be represent as Integer (for example 3.0, 5.0 etc.) i want to add it as Integer, otherwise as double.

The first method to realize this is:

StringBuilder sb = new StringBuilder();
double d = 3.5;

if (d % 1 == 0) sb.append((int) d);
else sb.append(d);

System.out.println(sb.toString());

This works still good, when d is 3.0 3 will be append, if d is 3.5 3.5 will be append.

Now i want to do this shortly with the ternary operator:

StringBuilder sb = new StringBuilder();
double d = 3.5;

sb.append(d % 1 == 0 ? (int) d : d);

System.out.println(sb.toString());

So now i have an issue, every time, if double is 3.0 or 3.5 it will be added as double value! Only when i theoretically cast on true AND false it works... but every time and that is not what I want. What is here the problem? Why does the ternary operator not work?


Solution

  • The reason for this behaviour is that an expression with a ternary operator has a well-defined type. The JLS describes in some detail how this type is evaluated, but in rough terms, it's the least upper bound of the type of the expression before the colon and the type of the expression after the colon.

    For example, if b is boolean, i is int and d is double, then the type of b ? i : d is double, because double is the least upper bound of int and double. When you call append( b ? i : d ) on your StringBuilder, you get the version of append with the double parameter. The same thing happens in your case, with d % 1 == 0 ? (int) d : d.