ternary operator produces a string – I’m concatenating these phrases. Unable to understand and explain Java… here is a solution to the problem.
ternary operator produces a string – I’m concatenating these phrases. Unable to understand and explain Java
String loggerKey = "srini";
String loggerDescription = "vas";
System.out.println(loggerKey != null?loggerKey:""+loggerDescription != null?loggerDescription:"");
The code above gave me the result Srini, and I’m expecting Srinivas. But if I modify the code to the following, I’ll get Srinivas as output.
String loggerKey = "srini";
String loggerDescription = "vas";
System.out.println((loggerKey != null?loggerKey:"")+(loggerDescription != null?loggerDescription:""));
How is the first fragment interpreted by Java? That’s what I was looking forward to.
String loggerKey = "srini";
String loggerDescription = "vas";
System.out.println((loggerKey != null?loggerKey:"")+(loggerDescription != null?loggerDescription:""));
String loggerKey = "srini";
String loggerDescription = "vas";
System.out.println(loggerKey != null?loggerKey:""+loggerDescription != null?loggerDescription:"");
Output:
Srinivas
Solution
Because of operator precedence rules, your composite ternary is actually evaluated as:
loggerKey != null ? loggerKey : ("" + loggerDescription != null ?
loggerDescription : "")
That is,
although the vas
description is assigned, it is part of the second else predicate of the first outer ternary statement and is therefore skipped because the key srini
is not empty.
The solution that you put parentheses around each individual ternary is correct and is a solution to your problem.