BAD OPTIMIZATION USING STRINGS When there is a need to optimize the performance of Java code, the suspicion usually falls on Strings. Although this is a good place to start, sometimes developers overdo the optimization and create bad code. It is a common mistake to think that if a String is constant, then it should be changed to a static final variable to improve performance. This is often accomplished with SQL statements. public class Example { static private final String SELECT_FROG = "SELECT * FROM Frog where x=?"; ..... ..... public void doSomething(int x) { ... ... Statement stmt = connection. prepareStatement(SELECT_FROG); stmt.setInt(x); ... } } This overdone optimization quickly leads to a class in which all the SQL statements have been converted to Java constants and the top of the class. Each time a reader tries to understand the storage logic, the reader has to flit backwards and forwards between doSomething and the SELECT_FROG static attribute. As is so often the case, the optimization leads to harder-to-read code. And actually, the performance is not really enhanced. Java compilers are perfectly able to handle the optimization of String literals. This even works if the literal is split over lines with the + symbol. The correct way to write the above code would be the far simpler and faster: public class Example { ..... ..... public void doSomething(int x) { String sql = "SELECT * FROM Frog where x=?"; ... ... Statement stmt = connection. prepareStatement(sql); stmt.setInt(x); ... } } If the line of SQL is long, then it is perfectly fine, and in fact desirable, to do: String sql = "SELECT name, place, age, id " + " FROM Record " + " WHERE name LIKE 'john' "; ----------------------------------------