I've come across a class that includes multiple uses of a string literal, "foo".
What I'd like to know, is what are the benefits and impact (in terms of object creation, memory usage and speed) of using this approach instead of declaring the String as final and replacing all the literals with the final variable?
For example (although obviously not a real word usage):
private static final String FINAL_STRING = "foo"; public void stringPrinter(){ for(int i=0;i<10;i++){ System.out.println(FINAL_STRING); } }
Versus:
public void stringPrinter(){ for(int i=0;i<10;i++){ System.out.println("foo"); } }
Which is preferable and why (assuming the string value will remain constant)?
Would the above (second) example result in 10 String objects being created or would the JVM realise that only a single literal is actually used, and create a single reference. If so, is there any advantage for declaring the String as final (as in the first example)?
If the interpreted code does replace the string literal with a single reference, does that still apply if the same literal occurs in more than one place:
public void stringPrinter(){ for(int i=0;i<5;i++){ System.out.println("foo"); // first occurence System.out.println("foo"); // second occurence } }
A literal is a value that is expressed as itself. For example, the number 25 or the string "Hello World" are both literals. A variable in a program can change its value during the course of execution of the program.
The main difference between String Literal and String Object is that String Literal is a String created using double quotes while String Object is a String created using the new() operator. String is a set of characters.
A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string. You must always prefix wide-string literals with the letter L.
When you use a string literal the string can be interned, but when you use a new String("...") you get a new string object. In general, you should use the string literal notation when possible. It is easier to read and it gives the compiler a chance to optimize your code.
They will be exactly the same. The literal is interned (any compile time constant expression that results in that string shares the same instance as all other constants/literals) in both cases and a smart compiler+runtime should have no trouble reducing both to the most optimized example.
The advantage comes more in maintainability. If you want to change the literal, you would need only change one occurrence with a constant but you would need to search and change every instance if they were included inline.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With