Is there any difference between the concatination of Strings using (+) operator and concat() method of String class.
I guess there is some difference. Can any one let me know the difference....
Deepak Jain
Ranch Hand
Joined: Aug 05, 2006
Posts: 637
posted
0
I dont think there is any difference between + and concat() wrf to Strings. Even the behavior and the output is the same. concat() will concantenate s2 and s3 in a new String object and so will + operator and return the reference of the new String object. Thanks Deepak
SCJP, SCWCD, SCBCD
Fu Dong Jia
Ranch Hand
Joined: May 23, 2007
Posts: 131
posted
0
hi I am agree with Deepak Jain. there is no different between + and concat().
who dare win!<br />SCJP5(94%)|SCWCD5(86%)|SCBCD(100%)|SCEA in progress
Kishore Kumar
Ranch Hand
Joined: Oct 15, 2007
Posts: 71
posted
0
But when i gone through the API for String class i found this..
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. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java.
But i am not able to understand clearly about this. Can anyone make this clear to me.
Deepak Jain
Ranch Hand
Joined: Aug 05, 2006
Posts: 637
posted
0
I think its like this String s1 = s2 + s3; Here JVM will first construct a StringBuilder [Non synchronized] objects for s2 and s3 and then invoke s2.append(s3) and assign the object to s1. If you observe here two StringBuilder objects are created for s2 and s3 and since StringBuilder objects are mutable while appending s2 to s3 no new STring objects are created and finally its assigned to s1.
String s1 = s1.concat(s2) s1 is concantenated to s2 in a new STring object and this new String object is then assigned to s1. Still i feel there is no difference btw + and concat in terms of number of objects that were created. Thanks Deepak
Second Question is If StringBuilder s5 = new StringBuilder(null); and StringBuffer s = new StringBuffer(null); do not throw "Compiler Error" Why does String s66 = new String(null); throw a compiler error "The constructor String(String) is ambiguous" This example was tested with Eclipse and With Java 1.5 Thanks Deepak
I am not very sure about the StringBuilder class as i m just now getting into Java 5.
But as far as i know, the + operator gets resolved at the compile time and during the class loading operation, the concatenated string is available in the String Literal pool and ready to serve. Whereas in case of the methods like concat(), the concaneated string gets prepared only during runtime.
One comment: strictly speaking, the mapping of string concatenation to StringBuilder/StringBuffer is not mandated by the JLS. Each implementation is free to choose to use StringBuilders only in certain circumstances (e.g. when at least four strings are being concatenated together), to use a different data structure, or to not do any optimization at all. So this is technically an implementation-specific behavior.
However, as far as I know, practically all Java compilers do optimize string concatenations with StringBuilder (for Java 1.5+) or StringBuffer (up to Java 1.4) whenever they can.
SCJP 5.0
Deepak Jain
Ranch Hand
Joined: Aug 05, 2006
Posts: 637
posted
0
But as far as i know, the + operator gets resolved at the compile time and during the class loading operation, the concatenated string is available in the String Literal pool and ready to serve. Whereas in case of the methods like concat(), the concaneated string gets prepared only during runtime
How can String pool [Strings inside the string pool] be available at compile time. String pool will be constructed with STring literals in the program, only when the program runs.
Kelvin Chenhao Lim
Ranch Hand
Joined: Oct 20, 2007
Posts: 513
posted
0
Originally posted by Raghavan Muthu: But as far as i know, the + operator gets resolved at the compile time and during the class loading operation, the concatenated string is available in the String Literal pool and ready to serve.
Note that this is true only for concatenation of strings that are compile-time constants. For example, this code points out a few subtleties:
Deepak Jain
Ranch Hand
Joined: Aug 05, 2006
Posts: 637
posted
0
Thanks Kevin. The example is really very good.
Deepak Jain
Ranch Hand
Joined: Aug 05, 2006
Posts: 637
posted
0
Hi Kelvin, I do understand your example very clearly. But i have a doubt String a = "XYZ"; String c = "X"; String b = c+"YZ"; System.out.println(a==b);
Here during the compilation of c+"YZ" c is not a final variable[compile time constant] and hence "XYZ" will not be availble in the string pool. So finally when the program runs.
String a = "XYZ" this line will construct a new STring "XYZ" in the string pool and a will refer to it.
String c = "X"; this line will construct a new STring "X" in the string pool and a will refer to it.
1) String b = c+"YZ"; Here "YZ" will be placed in String pool during compile time itself.Now when c+"YZ" runs the result is "XYZ" which is already availble in String pool, Why doesnt JVM assign b to that string instead of constructing a new String object. Isn;t this waste of memory since Strings are immutable? [ November 22, 2007: Message edited by: Deepak Jain ]
dhwani mathur
Ranch Hand
Joined: May 08, 2007
Posts: 621
posted
0
Hi All
Please can anyone explain the example given by Kelvin ,i am just confused
with the output as shown............ why here it is false?although getFo() method will return Fo as shown static String getFo() { return "Fo"; }
any help on the above doubt will be realy kinda of you..............
Thanks in advance ........
Kelvin Chenhao Lim
Ranch Hand
Joined: Oct 20, 2007
Posts: 513
posted
0
Originally posted by Deepak Jain: Why doesnt JVM assign b to that string instead of constructing a new String object. Isn;t this waste of memory since Strings are immutable?
Hi Deepak,
There are at least two reasons.
Firstly, this preserves flexibility for the times when you as the programmer may actually want a new String object. This is similar to why the String class has a constructor that takes a String parameter to produce a new String object with the same value.
Secondly and more importantly, it's a relatively expensive operation to look up the string literal pool table for an existing String object with the same value. If every single string operation did this to avoid reallocating the memory for a string, this will greatly slow down string operations in general. It's ok to do this when loading a class, since that's just a one-off thing per class. But the performance cost of automatically doing this for other string operations is probably not worth the tradeoff for the memory savings.
If you really want to use the string literal pool for runtime-generated strings, that's what String's intern() method is for.
Hope this helps! [ November 22, 2007: Message edited by: Kelvin Lim ]
Deepak Jain
Ranch Hand
Joined: Aug 05, 2006
Posts: 637
posted
0
Kelvin, Once again thanks and detailed explanation and also thanks for intern(), When i read about intern() I was wondering why would anybody want to use that since strings are always used from pool [cached]. One last thing to clarify is So strings will be picked from string pool only during assignment? like String a = "aaa"; String b = "aaa"; And during concantenation using + operator if the strings are not compile time constants then again new strings will be created.
Today, i have really enhanced my knowledge on String pools. Thanks to you and forum.
dhwani mathur,
1. Since getFo() method needs to be run and its not a compile time constant, new string will be created and hence s0 == s2 will be false. 2. Here b1 is again not a compile time constant i.e., its not a final constant which means b1 can change during execution. Suppose b1 was final then at compile time it would have known taht s9 = s6 + "Bar" , Now if at compile time if s6 value is known i.e., if s6 is a final variable then s0 == s9 will be true. But since b1 is not a final constant s0 == s9 will be false which means a new string will be created and assigned to s9.
I hope this clears your doubt. Thanks Deepak [ November 22, 2007: Message edited by: Deepak Jain ]
Kelvin Chenhao Lim
Ranch Hand
Joined: Oct 20, 2007
Posts: 513
posted
0
Originally posted by Deepak Jain: One last thing to clarify is So strings will be picked from string pool only during assignment? like String a = "aaa"; String b = "aaa";
Not just during assignment. Compile-time string constants will be taken from the string pool wherever they're used within any other expression.
For example, all four occurrences of the string literal "bar" in the following program will refer to the same string pool object at runtime, although only one of them occurs as an initializer. Observe that this is true even across multiple classes:
[ November 22, 2007: Message edited by: Kelvin Lim ]
dhwani mathur
Ranch Hand
Joined: May 08, 2007
Posts: 621
posted
0
Hi !!
Thanks a lot Deepak Jain for your explanation...... now i am clear with my doubt...!!!
Dhwani:>Its alaways too soon to quit!!
Deepak Jain
Ranch Hand
Joined: Aug 05, 2006
Posts: 637
posted
0
I like when people call me deepu So you can call me deepu or deepak will do just fine. Thanks to Kelvin. [ November 23, 2007: Message edited by: Deepak Jain ]
Burkhard Hassel
Ranch Hand
Joined: Aug 25, 2006
Posts: 1274
posted
0
Howdy ranchers,
back to the original question.
Doing the concatenation on Strings with plus is slower than using the concat method. And both cannot compare to using a StringBuilder. Example code
My output was:
concat: length: 60000 1969 ms plus: length: 60000 15109 ms StringBuilder: length: 60000 16 ms
Yours, Bu.
all events occur in real time
Nabila Mohammad
Ranch Hand
Joined: Nov 05, 2007
Posts: 661
posted
0
Can some one explain this?? I kind of got it But still want to know what's going behind the curtains!
[ November 23, 2007: Message edited by: Nabila Mohammad ]
The future belongs to those who believe in the beauty of their dreams.Dream BIG!
Deepak Jain
Ranch Hand
Joined: Aug 05, 2006
Posts: 637
posted
0
Bu, That was a really good insight. After i ran the code, here is the outcome
length: 60000 782 ms plus: length: 60000 781 ms StringBuilder: length: 60000 16 ms StringBuilder is very fast. So we should always use StringBuilder.concat to concantenate strings.
I added
This takes same time as StringBuilder. And infact when the above method is invoked with StringBuilder, StringBuilder takes 0ms . So it was good to know that concatenation should always be done with StringBuilder or StringBuffer based on synchronization needs and never with + or String.concat() . That was cool.
Coming to the question final String s11 = s3; Here s3 is not a final String and therfore not a compile time constant and hence the result is false.
And the next final String s13 = s6; Here s6 is a final String and hence a compile time constant and therefore the result is true. Thanks Deepak
Kelvin Chenhao Lim
Ranch Hand
Joined: Oct 20, 2007
Posts: 513
posted
0
Originally posted by Deepak Jain: So it was good to know that concatenation should always be done with StringBuilder or StringBuffer based on synchronization needs and never with + or String.concat() .
Be careful not to make this conclusion too broad. You definitely should use an explicit StringBuilder/StringBuffer when you are doing a lot of concatenations in a loop or across multiple statements (which was the example that Bu presented). But when you're just doing a one-off concatenation operation, then using the + operator is perfectly fine (and is usually exactly the same as using StringBuilder/StringBuffer, since that's what most compilers optimize it to.)
The reason why the + operator is slower in a loop is that it does a lot of needless conversions from String to StringBuilder and vice versa. In other words,
is basically the same as: which of course involves a lot of avoidable StringBuilder instantiations and toString() conversions.
But the + operator is perfectly fine for many other cases, and it is arguably preferred because of its greater readability.
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
posted
0
Using + can even be faster than StringBuilder or concat(), if the entire expression consists of compile-time constants. Because in that case, the entire expression will be evalutated at compile time. That's not possible if you explicitly use StringBuilder or the concat() method. Sometimes using + is best, both for readability and performance reasons. However these performance issues are usually very minor - the only time it can make a big difference is if you incorrectly use + inside a loop which is building a progressively larger string, as Bu showed. That's the one common case where using + can be a big mistake. For most other cases it really doesn't matter very much.
That's a great discussion. Bu's example was perfect and Kelvin has explained clearly on what is happening behind the scenes with "+" and thats the reason it seems to be slower. Jim's conclusion is also well agreeable.
One thing i feel somehow missed is, Deepak [Or Deepu ]'s question
Here in line 3 it seems to be creating a new String object because of the "+" operator. And since those reference variables are NOT compile time constants (final), they are evaluated at runtime.
Hope this adds a little value!
Bert Bates
author
Sheriff
Joined: Oct 14, 2002
Posts: 8712
posted
0
FYI - this conversation is very interesting and it's also WAY deeper than the real exam will go. For those of you who are focused on the exam, you won't have to know this stuff.
hth,
Bert
Eliminate fossil fuel subsidies. (If you're not on the edge, you're taking up too much room.)