0

In this answer, in handleTestCaseFinished() the value of String id starts with "". Why is that? (Not singling this answer out, I've seen it somewhere else before, but this one prompted me to get an answer.)

Choosing search terms for Google has proven to be particularly difficult.

I've tested this with:

String s1 = System.getenv("JAVA_HOME");
String s2 = "" + System.getenv("JAVA_HOME");

System.out.println(s1.equals(s2) ? "true" : "false");

I also didn't notice a difference using the debugger in IntelliJ IDEA. Maybe this was not the way to test this?

Brazen
  • 295
  • 3
  • 10
  • 1
    Probably just a quick way to make a string out of the result of `testCase.getUri()` and continue on concatenating strings. Without that, one would have to do `testCase.getUri().toString() + ...`, and the behavior wouldn't exactly be the same. – ernest_k May 10 '21 at 04:50
  • It's a quick and dirty way to converting any value to a String. – code May 10 '21 at 04:54
  • 3
    `"" + x` is equivalent to `String.valueOf(x)`. – Andy Turner May 10 '21 at 05:47

2 Answers2

1

Mostly to avoid ending with null and eventually null pointer exception. In this case by default it will end up with "null" string. [Edited, thanks Ernest_k]

Siva_M7
  • 11
  • 2
  • If `testCase.getUri()` returns null, then `"" + testCase.getUri()` will be the string `"null"`, not `""`. – ernest_k May 10 '21 at 05:31
1

Java treats + as a String concatenation operator only if one or both of its operands are strings. If both are numbers, + is the numeric addition operator. For any other operands, it's an error.

In that answer, the line isn't quite what you've shown:

String id = "" + testCase.getUri() + testCase.getLine();

i.e. there are two concatenations.

Presumably, both of these other operands are not strings and at least one isn't a number. Attempting to + two things which aren't both numbers and aren't both Strings would be a compiler error.

Prepending "" means that they are converted to Strings, and concatenated, because of the right associativity of +:

String id =        (  ""   + testCase.getUri()) + testCase.getLine();
             //    (String + non-String       ) + (non-String)
             // =>       String                 + non-String
             // =>                           String
Andy Turner
  • 137,514
  • 11
  • 162
  • 243