tags:

views:

59

answers:

3

Given the following snippet A

private static final String SQL = "SELECT * FROM TABLE WHERE ID = ?";

and snippet B

public List<MyObject> getData(final Long id){
    return (List<MyObject>)template.query("SELECT * FROM TABLE WHERE ID = ?",id);
}

and snippet C

public List<MyObject> getData(final Long id){
    return (List<MyObject>)template.query(SQL,id);
}

Are B and C effectively the same? Does my string in B get gc'd (young generation?) because it has local scope?

+1  A: 

No. Neither B nor C create a String. The String will be created when the code is loaded (if it does not already exist as an interned String). It will be garbage collected along with the rest of the code (unless there is another reference to the same String instance).

Tom Hawtin - tackline
+2  A: 

String constants are always interned. Every time you call snippet B it will use the same string object. Basically it's equivalent to snippet A+C.

Indeed, two string constants which have the same sequence of characters will use references to the same string too:

String x = "a" + "b";
String y = "ab";

System.out.println(x == y); // true
Jon Skeet
So, in other words, if I used B my local string is not interned and would be garbage collected but in C the string SQL will be interned and not be GC'd
non sequitor
no, you did not read the answer correctly. all your snippets result in an interned string.
james
+1  A: 

Both B and C use the same string value, since all strings are essentially "cached" by the JVM. They exist in memory as long as they need to.

Whether to use B or C is a matter of code readability (and maintainability). Approach B offers the advantage that the SQL query string is immediately adjacent to the code that uses its results, so there should be no question as to what the query is at the point it's being used.

Approach C is advantageous if you're using the same SQL query string in many places, allowing you to define the string once for the whole class (or package, even). If you ever have to change it everywhere it's used, you only need to change that one definition.

Loadmaster