Results 1 to 4 of 4
- 03-25-2010, 06:34 PM #1
Member
- Join Date
- Mar 2010
- Posts
- 6
- Rep Power
- 0
What is the difference between Inline literal and Static final String in Java.
e.g.
Code1:
String name = "John" + "Hooper";
Code 2:
static final String JOHN = "John";
static final String HOOPER = "Hooper";
String name = JOHN + HOOPER;
What is the underneath difference in these two approaches. Is there any performance or memory gain in second approach.
Thanks
- 03-25-2010, 07:17 PM #2
Senior Member
- Join Date
- Jun 2008
- Posts
- 2,366
- Rep Power
- 8
No gain, a (very little) more memory used in the second approach. Where the second approach has benefits os when the same string is to be used mutliple times, as it allows you to change the string in one place and have it changed everywhere, but, if this is not what you need then it makes no sense to do that.
- 03-26-2010, 04:25 AM #3
Member
- Join Date
- Mar 2010
- Posts
- 6
- Rep Power
- 0
Masijade, Thanks for the reply
How internally string constants are stored in JVM
I read somewhere that the time required to access static final String is less then the string literal.
- 03-26-2010, 07:09 AM #4
Senior Member
- Join Date
- Jun 2008
- Posts
- 2,366
- Rep Power
- 8
No. You will reference (access) it through a reference like any other String. What takes "longer" with String literals in the "interning" process (i.e. creating/defining it), but this is negligible as long as you are not doing it constantly. You still have to intern the String literal in the declaration of the final variable (and the interning only happens once regardless of how many times that same String literal is used through out the class), so declaring the variable doesn't help, except, maybe, when that variable is being referenced from multiple classes, and, again, that is neglible in the case of String literals (as it happens only once per String literal, per class, the compiler takes care of that). What you don't want to do with "interning" is call the intern method on every String object you create.
Similar Threads
-
Newbie help on visibility and static final
By tornado in forum New To JavaReplies: 3Last Post: 11-28-2008, 01:32 AM -
static final field
By techie.it19 in forum New To JavaReplies: 3Last Post: 10-16-2008, 04:12 AM -
Final,abstract and static
By $hr!k@nt in forum Advanced JavaReplies: 5Last Post: 01-09-2008, 05:23 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks