String concatenation - value Off or not

So, I just looked for a while, all the different questions here are about .valueOfwith strings, but they all seem to relate to conversions. Comparing .valueOfonly with + "".

I want to know if it is worth it or should be used at all .valueOfif it is concatenation.

Example:

LOGGER.info("Final Score: " + String.valueOf(Math.round(finalScore * 100)) + "%");

VS

LOGGER.info("Final Score: " + Math.round(finalScore * 100) + "%");

It seems that use is String.valueOfnot required if you have the actual lines to go along with it. I understand that it is better to use .valueOfif you just convert it and intend to use an empty string.

+4
source share
3 answers
+3

String#valueOf(Object) :

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

, valueOf toString , valueOf . , , .

Object foo = null;
System.out.println("foo " + foo); //foo null, no exception thrown
System.out.println("foo " + String.valueOf(foo)); //foo null, no exception thrown

, , valueOf .

+1

You're right. When you concatenate strings and other data types, Of is not required. For int only, I think valueOf works, but, by analogy, the second example is much more common

@Test
public void testStringValueOF(){
    int num = 123;

    // this works...
    String test = String.valueOf(num);

    // but this is more common
    String test2 = "" + num;
}
0
source

Source: https://habr.com/ru/post/1669977/


All Articles