Thursday, April 11, 2024

How String concatenation works in Java?

You can concatenate multiple String using + operator in Java. Even though Java doesn't support operator overloading, + operator is special, it performs addition if given operands are numeric and does String concatenation if one of them is String. Why it's important to know how String concatenation works? Well, more often that you can live without this knowledge but if you want to master Java then why not know little more detail. Apart from that it also helps you to avoid a performance mistake, which many Java devleoper do, concatenating String inside loop. When you concate two String literal e.g. "abc" + "cde" then compiler do this concatenation at compile time and this doesn't involve StringBuilder.


Concatenating two String literal



Concatenating String literal and String variable.




Things to remember:

1) Don't concatenate String in loop because Java creates a new StringBuilder() every iteration.

2) If two String literal are concatenated i.e. "Java" + "Script" then it happens at compilation time

2) When you concatenate a String literal and a String object, or two String object then it happens at runtime.




That's all about how String concatenation works in Java. 


No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.