If we take a look at your specific example, then the first is better, because the compiler is smart enough to concatenate the strings "javaRanch" + " is" + " good" + " site" at compile time. So, writing:
Note however, that if you use the + operator to concatenate strings that are not compile-time constants, the compiler will convert this automatically to code that uses StringBuffer (or StringBuilder). That can be less efficient than using StringBuilder yourself. Have a look at the following example:
The compiler will automatically convert this to something like this:
This is quite inefficient code: in every iteration of the loop, a new StringBuilder object is created, the contents of 'result' is copied into it, then a value is concatenated to it, and then the content of the StringBuilder is copied into a new String object again which is assigned to 'result'. So, there are a lot of temporary objects and a lot of copying of data going on.
Suppose you wrote it yourself like this:
That is a lot more efficient - there is only one StringBuilder object, and no unnecessary copying. [ May 15, 2008: Message edited by: Jesper Young ]
Originally posted by Sunny Jain: Jasper, I have one more query :
Try thinking about it yourself.
Note the following: If you have compile-time constants (values of which the value is fixed at compile time), the compiler will do the work beforehand. If not, then the compiler will convert the code to something with StringBuilder.
Look at your code, and think about what the compiler would do with it.
Note that problems with inefficiency especially happen when you use + on strings inside a loop - it's not such a problem when it's not in a loop.