Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Concatenation - valueOf or not

Tags:

java

string

So I just perused for a while, all the different questions on here about .valueOf with strings, but they all seem to be about conversions. Comparing .valueOf to just + "".

I want to know if it is worth it or at all necessary to use .valueOf if it is a concatenation.

Example:

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

VS

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

It seems as though using String.valueOf is unnecessary if you have actual strings to go along with it. I understand it may be better to use .valueOf if you were just converting it and intended to use an empty string.

like image 272
n_plum Avatar asked Feb 16 '17 19:02

n_plum


People also ask

What is the difference between toString () and valueOf () in Java?

String. valueOf will transform a given object that is null to the String "null" , whereas . toString() will throw a NullPointerException . The compiler will use String.

What are the 2 methods used for string concatenation?

There are two ways to concatenate strings in Java: By + (String concatenation) operator. By concat() method.

Can you use += for string concatenation?

The + Operator The same + operator you use for adding two numbers can be used to concatenate two strings. You can also use += , where a += b is a shorthand for a = a + b .


2 Answers

The source code for String#valueOf(Object) looks like this:

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

So the only difference between valueOf and toString is that valueOf is null-safe. So let's see which one is used if we concatenate a string and an object.

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

So it looks like there's no difference whatsoever between concatenation and using valueOf in this context.

like image 22
CollinD Avatar answered Oct 12 '22 13:10

CollinD


When we concatenate strings, the compiler actually translates it to StringBuffer.append().

The underlying implementations for StringBuffer.append(int) and String.valueOf(int) both eventually end up calling Integer.getChars(int,int,char[]) except that in case of String.valueOf(), there is a call to Integer.toString(int) first.

To conclude, for the given scenario, directly concatenating would be the way to go. But if you intend to be conscious about memory, then use string-builder to concatenate values first and then log it.

like image 98
Ravindra HV Avatar answered Oct 12 '22 11:10

Ravindra HV