Friday, August 1, 2014

Compiler version : How String concatenation works in java.

The designers of Java decided to retain primitive types in an object - oriented language, instead of making everything an object. String class is one of them.String is the one of the most using(also confusing) class in Java. It is the class most used since to convey something(content), we need Information which is in the form of String.If someone showing / sending some information or passing some username / password to some system, what not most of the business depends on String only.

Not going in to very details of String class let 's discuss on concatenation alone. As we discussed in the very first line, to retain primitive types and operations designers almost succeeded and made the literal type declaration (String s=" str") and concatenation like math operation addition (String res="this"+"and this"). The same thing mentioned in String class documentation as well.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. 

According to the specification what they mean is, If you write the below line and adding two Strings(with +)results in the combined String.

 String testString ="str"+"ingcon"+"catenation";  

If we print the above declared String to console and see, the result is stringconcatenation.Which is correct and the + works fine. Here is out actual question, how does that + symbol did the magic ? ? Is it not a normal mathematical addition of Strings. The below code snippet shows how that code with + actually converts.

 StringBuilder compilerGeneratedBuilder = new StringBuilder();  
 String finalString = compilerGeneratedBuilder.toString();  

Next >> Why do I use extensively.

No comments:

Post a Comment