1

What does this snippet of code mean?

int value;
if (value > 0)
 String input = "" + value;
2
  • 4
    It's a rather grim way of getting the compiler to automatically convert an int into a String. Commented Oct 17, 2013 at 1:40
  • 3
    That's a lot of code for one line that needs explanation. Commented Oct 17, 2013 at 1:43

3 Answers 3

10

It is converting value to a string. "" + value is very similar to value.toString(). The "" means the compiler is looking for a string after the +, so when it sees value in that space, it automatically calls value.toString() to produce the string result.

Sign up to request clarification or add additional context in comments.

4 Comments

More like Integer.toString(value), since it's an int, but the idea is the same (+1).
Using '+' with strings is a quite bad practice. The developer should use value.toString() or a StringBuilder (at least).
@air-dex That depends on the context. In a loop for example it could be considered bad practice, but for a one-time concatenation it is generally fine. Of course in this specific case the Integer.toString() approach is to be preferred.
@air-dex not necessarily on the StringBuilder. The compiler automatically converts inline concatenations into the StringBuilder approach, but the concatenation approach is more readable. The StringBuilder should only be used if the concatenation is occurring, for instance, in a loop, where the StringBuilder would need to be declared before the loop instead of inline as the compiler does.
2

String input = "" + value; value is an integer type. adding it to empty string-"" just making it a string. Suppose value = 3, then ""+value will be "3"

Edit: Forgot to mention about String.valueOf(val) function, another static utility method to convert almost all primitive type to String.

Comments

0

Compiler know how to add an integer with some string value. So in the code rather calling directly the integer to string conversion method. The coder generates an constant string ""(having no value in it) and then call concatenation operator(+) overloaded method to add and cast the integer into string value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.