Home



2017/05 - Concatenation in Java

Concatenation is a funny little thing in Java. The plus(+) operator is overloaded, meaning that we can add numeric values as well and text strings. We can add numbers together, and join text. Consider the following code snippet:

Integer three = 1+2 //Result: 3

String testString = "new" + " string here!" //Result: "new string here!"

 

What happens when we join numbers and text though?

String testString = 1 + 2 + "3" //Result: "33"

 

The reason for this is the order in which Java interprets the values we're trying to "join" or otherwise concatenate. It is left to right, numeric values are calculated and strings are concatenated. When a string is involved in a calculation and one value is numeric, it is converted into a string. So really, in the above statement we're adding the numbers 1 and 2, then concatenating the strings "3" and "3".  This basically means that, once we hit a string, the rest of the calculation is treated as a string. Because once we concat a string, the left side of the evaluated calculation will always be a string. For example, what happens when we do this?

String stringsLandPopulationYou = "1" + 2 + 3 + 4; //Result: "1234"

 

Basically we start with a string and it doesn't matter if the rest of the evaluation is numeric or not, they'll all be treated as strings. 

 


 

Also, the String pool in Java isn't used if you keep telling Java to create a new string:

String s = new String("I'm a new String! :D")

Instead, you'll want to tell Java that you want to pick up a string from the string pool if it exists and use that instead of creating a new string object:

String s = "I'm an existing String! :D"

This is just a little extra info for those have issues with performance and memory. If you're dealing with large amounts of text, this kind of programming can help you avoid inefficiency that slows applications down. 

Happy programming!