Results 1 to 4 of 4
  1. #1
    devaru2003 is offline Member
    Join Date
    Mar 2010
    Posts
    6
    Rep Power
    0

    Question 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

  2. #2
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    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.

  3. #3
    devaru2003 is offline Member
    Join Date
    Mar 2010
    Posts
    6
    Rep Power
    0

    Default

    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.

  4. #4
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    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

  1. Newbie help on visibility and static final
    By tornado in forum New To Java
    Replies: 3
    Last Post: 11-28-2008, 02:32 AM
  2. static final field
    By techie.it19 in forum New To Java
    Replies: 3
    Last Post: 10-16-2008, 05:12 AM
  3. Final,abstract and static
    By $hr!k@nt in forum Advanced Java
    Replies: 5
    Last Post: 01-09-2008, 06:23 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •