-1

I have integer status response from a REST API. I need to return string, so I use it like

return "" + statusCode

Is it fine way to do that or is it costly? Or should I use String.valueOf() or is there another alternative?

Abra
  • 19,142
  • 7
  • 29
  • 41
fatherazrael
  • 5,511
  • 16
  • 71
  • 155
  • "if consider space/time thing" what does that even means? – Stultuske May 19 '22 at 17:28
  • 3
    In the context of a network request, I think it's almost *certain* that this will be noise... but `String.valueOf(statusCode)` is the *cleanest* way to do it, IMO, because it says what you're trying to do: obtain the string representation of a value. You're not logically trying to perform any string concatenation. – Jon Skeet May 19 '22 at 17:29
  • There are lots of ways of converting an integer to a string, and no shared meaning for the word "costly". Benchmark and decide which option works best for you: https://stackoverflow.com/questions/5071040/java-convert-integer-to-string – user229044 May 19 '22 at 17:33
  • 1
    as Jon [wrote](https://stackoverflow.com/questions/72308775/is-converting-integer-to-string-by-appending-it-to-double-quotes-like-return#comment127745380_72308775), using `valueOf()` or, as I prefer (for *reading*), `Integer.toString(statusCode)` is better to communicate what you want to accomplish. Concatenation is probably a little bit more *expensive* unless the compiler is smart enough to eliminate it (OPenJDK's does NOT), but I doubt the difference will be relevant compared to network performance – user16320675 May 19 '22 at 18:09

1 Answers1

0

No need - if you decompile the class file, you'll see that the compiler does this for you anyway. I think this makes the code very readable, however you might want to ask yourself why are you doing this anyway... if you are confident that returning a number as a string from a method is correct, this is a good way to do it, IMO.

Ramsay Domloge
  • 695
  • 3
  • 11