Another question answered me how concatenation of String literals is evaluated in compile time. In a project I'm working on we handle multi-line Strings of big queries using a StringBuffer
. It appends just literals, so it had me thinking whether if something similar might happen.
In the following code, will the buffer append its contents at compile time? how would this behave when multiple threads are trying to execute this function?
public static String querySomething(int arg){
StringBuffer buffer = new StringBuffer();
buffer.append("A quite long query");
buffer.append("that doesn't fit in one line");
buffer.append("...");
}
Wouldn't it be better to define the String
as a constant since it would be thread safe and we know it can get concatenated at compile time with the plus operator. Something like:
private final static REALLY_LONG_QUERY1 = "A quite long query that"
+"doesn't fit in one line"
+"...";