1

I am simply trying to handle null String concatenation with below syntax and both are not compiling - Invalid Assignment Operator and Type Mismacth: can not convert fron null to boolean

String claimId = String.valueOf(VO.getClaimId());
StringBuffer strBuffer = new StringBuffer();
claimId == null?strBuffer.append(""):strBuffer.append(claimId);

OR

String claimId = String.valueOf(VO.getClaimId());
StringBuffer strBuffer = new StringBuffer();
(claimId == null)?strBuffer.append(""):strBuffer.append(claimId);

I simply want to append empty string if claimId String is null and append claimId otherwise.

What works is like,

String tempClaimId = (claimId == null)?"":claimId;

Later I can append tempClaimId to strBuffer

is Assignment expression mandatory here? Can't ternary operator syntax just be used to call methods?

How can I handle calling append with ternary without creating temporary Strings? OR do I just use if-else.

Sabir Khan
  • 9,826
  • 7
  • 45
  • 98
  • 6
    The conditional operator ([the correct name for `?:`](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25)) is an expression, not a statement. – Andy Turner Oct 10 '16 at 07:04
  • 2
    `strBuffer.append((claimId == null) ? "" : claimId);` would work (which is basically the same as the temporary variable approach, just without the temporary variable). – Andy Turner Oct 10 '16 at 07:05
  • There are also methods in libraries like Guava for converting `null` to `""`: [`Strings.nullToEmpty(String)`](https://google.github.io/guava/releases/19.0/api/docs/com/google/common/base/Strings.html#nullToEmpty(java.lang.String)). – Andy Turner Oct 10 '16 at 07:09
  • yes, you are correct about it being an expression and not a statement. Thanks for helping. – Sabir Khan Oct 10 '16 at 07:11
  • @AndyTurner that is indeed true, but the OP could still be confused by this. The expression `a = b;` is an expression but is also a statement (or to be precise, it's an expression without the `;` and a statement with it). So why is it that some expressions such as `a = b` can also be statements but others can't? – Klitos Kyriacou Oct 10 '16 at 07:11
  • 2
    @KlitosKyriacou formally, it's because `ConditionalExpression` is not a [`StatementExpression`](https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-StatementExpression), which may be used as statements by following them with semicolons. `Assignment`, like `a = b`, is a `StatementExpression`. – Andy Turner Oct 10 '16 at 07:13

0 Answers0