Actually given your example, using string literals, it's more efficient to write:

String myString = "Something" + "Something Else";

because the compiler doesn't need to concatenate these at runtime.

If you aren't using string literals, but variables instead, which do need to be concatenated at runtime, this is actually what the compiler does behind the scenes when you concatenate strings in a single expression anyway, even if you don't explicitly use StringBuffer--see the StringBuffer Javadoc.

In other words, this:

String myString = "SELECT " + columnlist + " FROM " + tablename + " WHERE " + keyname " = " + key;

and this:

StringBuffer sb = new StringBuffer("SELECT ");
sb.append(columnlist);
sb.append(" FROM ")'
sb.append(tablename);
sb.append(" WHERE ");
sb.append(keyname + " = " + key);
String myString = sb.toString();

are both equivalent to:

String myString = new StringBuffer("SELECT ").append(columnlist).append(" FROM ")append(tablename).append(
" WHERE ").append(keyname + " = " + key).toString();

Choosing between them is mostly a matter of style, unless the logic demands that you use multiple expressions.

- David Gallardo


At 01:07 PM 1/20/2003 -0800, Greg Nudelman wrote:
Just to add 2 cents more: here is another shortcut when you have to just use the StringBuffer in-place:

String myString = new StringBuffer().append("Something").append("Something Else").toString();

This one is best used for things like long dynamic SQL statements, etc. where you don't append in the loop, but still have a fair amount of the String objects to add.

____________________________________________________
David Gallardo | Software consultant | Author
Java, C/C++ software development | Database development | Internationalization
Author of "Java Oracle Database Development"


____________________________________________________
To change your JDJList options, please visit:
http://www.sys-con.com/java/list.cfm

Be respectful! Clean up your posts before replying
____________________________________________________

Reply via email to