String Pool

HI All,
When following assingments are done, then why two objects are created. According to string pool, only distinct objects exists for string in JVM. So == operator should return true. Till I was unaware of String Pool, it appeared right. But now I am a bit confused.
String s1="ab";
String s2="ab";
Kindly guide me on this. And point me to some good links about JVM, classloaders and String Pool. In books i am not able to find good coverage on these topics.

J2EE_Life wrote:
Kindly guide me on this. And point me to some good links about JVM, classloaders and String Pool. In books i am not able to find good coverage on these topics.That is because you shouldn't really care, except maybe for classloaders especially when you want to get into web development. Worrying about JVM internals only leads to bad behavior, like premature optimization.
For information about classloaders, there are numerous decent articles that Google can lead you to. the javadocs are a good place to start:
http://docs.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html

Similar Messages

  • What checks the String pool

    Hi there.
    With regard to the string pool,
    my book states that whenever the compiler
    encounters a string literal that it will check the pool to see if
    there is a matching string...
    This doesn't seem right to me.
    I would have imagined that the JVM would perform this operation at runtime.
    Maybe I'm wrong, but I googled it and I came across some sites that indicate that
    the JVM checks the string pool.
    Im just wondering which is it, the JVM or the compiler.
    Thanks & regards.

    jverd wrote:
    Both.
    String s1 = "abc";
    String s2 = "abc";Compiler sees the first line, looks for "abc" in the class' constant pool, doesn't find it, adds it, places reference to its position for the assignment to s1.
    Compiler sees the second line, looks for "abc", finds it, places reference to its position for the assignment to s2.
    At runtime, when class is loaded, VM loads class' String constant pool. When time comes to execute the above lines, the bytecode tells it which constant pool entry to reference.Great answer (No, I'm not sarcastic)

  • Why jvm maintains string pool only for string objects why not for other objects?

    why jvm maintains string pool only for string objects why not for other objects? why there is no pool for other objects? what is the specialty of string?

    rp0428 wrote:
    You might be aware of the fact that String is an immutable object, which means string object once created cannot be manipulated or modified. If we are going for such operation then we will be creating a new string out of that operation.
    It's a JVM design-time decision or rather better memory management. In programming it's quite a common case that we will define string with same values multiple times and having a pool to hold these data will be much efficient. Multiple references from program point/ refer to same object/ value.
    Please refer these links
    What is Java String Pool? | JournalDev
    Why String is Immutable in Java ? | Javalobby
    Sorry but you are spreading FALSE information. Also, that first article is WRONG - just as OP was wrong.
    This is NO SUCH THING as a 'string pool' in Java. There is a CONSTANT pool and that pool can include STRING CONSTANTS.
    It has NOTHING to do with immutability - it has to do with CONSTANTS.
    Just because a string is immutable does NOT mean it is a CONSTANT. And just because two strings have the exact same sequence of characters does NOT mean they use values from the constant pool.
    On the other hand class String offers the .intern() method to ensure that there is only one instance of class String for a certain sequence of characters, and the JVM calls it implicitly for literal strings and compile time string concatination results.
    Chapter 3. Lexical Structure
    In that sense the OPs question is valid, although the OP uses wrong wording.
    And the question is: what makes class Strings special so that it offers interning while other basic types don't.
    I don't know the answer.
    But in my opinion this is because of the hybrid nature of strings.
    In Java we have primitive types (int, float, double...) and Object types (Integer, Float, Double).
    The primitive types are consessons to C developers. Without primitive types you could not write simple equiations or comparisons (a = 2+3; if (a==5) ...). [autoboxing has not been there from the beginning...]
    The String class is different, almost something of both. You create String literals as you do with primitives (String a = "aString") and you can concatinate strings with the '+' operator. Nevertheless each string is an object.
    It should be common knowledge that strings should not be compared with '==' but because of the interning functionality this works surprisingly often.
    Since strings are so easy to create and each string is an object the lack ot the interning functionality would cause heavy memory consumption. Just look at your code how often you use the same string literal within your program.
    The memory problem is less important for other object types. Either because you create less equal objects of them or the benefit of pointing to the same object is less (eg. because the memory foot print of the individual objects is almost the same as the memory footpint of the references to it needed anyway).
    These are my personal thoughts.
    Hope this helps.
    bye
    TPD

  • The Literal String Pool...

    Hi guys...
    I wonder if someone could take the time to explain this to me?
    If we have the situation...
    String s1 = "ABC";
    String s2 = "ABC";
    if(s1==s2) {
        System.out.println("Same object");
    } else {
        System.out.println("NOT Same object");
    }Then we get;
    "Same object"
    There is only one string created and placed in the literal pool because they are identical.
    Fine.
    But, why then...
    String s1 = "ABC";
    String s2 = new String("ABC");
    if(s1==s2) {
        System.out.println("Same object");
    } else {
        System.out.println("NOT Same object");
    }... do we get;
    "NOT Same object"?
    I can definitly see how they are two different objects.
    But why arn't these identiacal with respect to the literal pool?
    I realise that I'm just going round and round in circles, but it's starting to bug me. One minute it makes sense, the next it doesn't.
    Cheers.
    Ollie Lord

    The constructor of string that you use copies the contents of the argument string to the new string and the new string is effectively a new object - it wont be in the literal pool because things like that can't be resolved in compile time.

  • Another string pool clarification

          public static void main(String[] args) {
              char[] diff = new char[]{'D','i','f','f','e','r'};
              String s = new String(diff);
              String t = new String(diff);
              System.out.println(System.identityHashCode(s));
              System.out.println(System.identityHashCode(s.intern()));
         }Both the sysouts print different values. Doesnt this mean there is an already existing reference in the pool? Any idea how that came?

    Yes you are right. But this was not for application coding purposes. So clarifying the intent.
         public static void main(String[] args) {
              String a = "hi";
              String b = "How";
              String c = "r";
              String d = "u";
              String abcd = a + b + c + d;
              System.out.println(abcd);
              char[] aA = new char[]{'h','i'};
              char[] aB = new char[]{'H','o','w'};
              char[] aC = new char[]{'r'};
              char[] aD = new char[]{'u'};
              char[] aABCD = new char[]{'h','i','H','o','w','r','u'};
              System.out.println(a == new String(aA).intern());  //prints true
              System.out.println(b == new String(aB).intern());  //prints true
              System.out.println(c == new String(aC).intern());  //prints true
              System.out.println(d == new String(aD).intern());  //prints true
              System.out.println(abcd == new String(aABCD).intern());  //prints false
         }Just wanted to be sure programatically how appending works exactly. Different forums and books are not so clear about it. Well the fact that string reference 'abcd' is not in the pool was something new to me (based on the assumption that at least that part of the javadoc for intern method is correct). But because of the change in spec for the intern method there is no way to check whether string "hiHow" is in the pool because we need a reference to it. But if the string abcd is not in the pool i guess "hiHow" will also not be.
    Thats the whole thing. And a conclusion, intern method will not let you help check the pool whether a string is in it, if you already dont have the reference to the literal and this is because of the change in the spec while implementation. If the javadoc were correct you could have done like below to see if the string is not in the pool.
         public static void main(String[] args) {
              char[] aAB = new char[]{'h','i','H','o','w'};
              String ab = new String(aAB);
              if(ab != ab.intern()){
                   System.out.println("alerady in pool");
              }else{
                   System.out.println("Only now in pool");
         }But now that the method puts a copy in the pool, we never know.

  • When is String literal pool created compile time or runtime?

    When is String literal pool created compile time or runtime?

    I have replied to your question in the other thread related to the string pool:
    http://forum.java.sun.com/thread.jsp?forum=31&thread=276893
    Pierre

  • Object creation of string

    Hello
    Please tell me what is the difference between these two object creation of string.
    String str = new String("Hello");.
    String str="Hello";
    Thanks.

    RGEO wrote:
    hello,
    Is the string pool is part of a heap? Huh? I suppose yes, you could regard the String pool as part of the heap... but (I guess) that interned String objects would be placed directly into the permanent generation, which is not garbage collected... and therefore I don't really think of the permanent generation as part of the heap (except when tuning heap allocations)... but I think I'm talking over your noob head here, yes... and so to the noob-stuff.
    If you get bored you might like to scan (for now) http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html#generations ... and come back to it in a couple of years time (when every second word isn't new and baffling to you;-)
    jvm what will do when he encounter the following code,
    String s1 = new String ("hello");The VM will:
    1. Create a new String object, and then
    2. copy the characters 'h','e','l','l','o' from the interned String "hello" to the new String,
    3. and then assign a reference to the new String to variable s1.
    Note that the result is subtley different from String s1 = "hello", which just does step 3... it assigns a reference to the existing interned String object "hello" to the variable s1... it does not create and "populate" a new String object.
    Try this just for fun... what is the output of the following program? Why?
    package forums;
    public class StringEquals
      public static void main(String[] args) {
        try {
          String a = "Hello";
          String b = "Hello";
          System.out.println("a==b is "+(a==b));
          String c = new String("Hello");
          System.out.println("a==c is "+(a==c));
        } catch (Exception e) {
          e.printStackTrace();
    }Now, what's the correct way to evaluate equality of String objects in Java?
    HTH. Cheers. Keith.

  • Strange String behaviour wrt ==

    The following code is disturbing my peace of mind (println is short for System.out.println):
    String s1="a"+"a", s2="aa", s3= new String("aa");
    println("aa"=="aa");
    println(s1==s2);
    println(s1==s3);
    On my JDK 1.2 this gives me:
    true
    true
    false
    I can - to a certain extend - live with the first interpretation, but the second and third ones really make my head spin: I have always thought that == on objects (and thus on String) was considered to be reference equality and that the "" way of describing Strings was mere syntactic sugar.
    But now I am in the dark. Is this an error in JDK or is Java suposed to work like this.
    Thanks in advance
    /Torben

    New java programmers always asks this. When you want to compare two strings, you should use s1.equals(s2), or s1.equalsIgnoreCase(s2). If you compare s1 == s2, it will not compare the strings. It will only be true if they have the same reference. However, there is a string pool, where strings hardcoded in your program are put, and if you do s1 = s1.intern(), then you will refer to the string in the pool. In the string pool, there will only be one occurance of each string.
    When you say String s1 = "a"+"a", then the compiler will read it as "aa", and this string are put in the pool. s2 = "aa" will use the same reference from the pool. s3 = new String("aa"), creates a new object, not in the pool.
    So s1 and s2 points to the same string, where s3 point to a string in another location, even though they are the same. Try add the line s3 = s3.intern(), then s1 == s3.
    Use the equals method when you want to compare strings.

  • Question about the java doc of String.intern() method

    hi all, my native language is not english, and i have a problem when reading the java doc of String.intern() method. the following text is extract from the documentation:
    When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
    i just don't know the "a reference to this String object is returned" part, does the "the reference to this String" means the string that the java keyword "this" represents or the string newly add to the string pool?
    eg,
    String s=new String("abc");  //create a string
    s.intern();  //add s to the string pool, and return what? s itself or the string just added to string pool?greate thanks!

    Except for primitives (byte, char, short, int, long, float, double, boolean), every value that you store in a variable, pass as a method parameter, return from a method, etc., is always a reference, never an object.
    String s  = "abc"; // s hold a reference to a String object containing chars "abc"
    foo(s); // we copy the reference in variable s and pass it to the foo() method.
    String foo(String s) {
      return s + "zzz"; // create a new String and return a reference that points to it.
    s.intern(); //add s to the string pool, and return what? s itself or the string just added to string pool?intern returns a reference to the String object that's held in the pool. It's not clear whether the String object is copied, or if it's just a reference to the original String object. It's also not relevant.

  • Which is better and why a = new String("AA") or a = "AA"

    Hi,
    Which is better and why
    String a = new String("AA") or
    String a = "AA"
    Does invoking a construtor waste memory? Please explain in detail.
    Thanks in advance
    Deepak

    > So in case "AA" not there in string pool,
    That is not correct.
    does new creates "AA" on string pool as well as heap memory?Yes. The literal "AA" points to a pooled String object. The new operator creates a new String object with the same character sequence ("AA"). You can verify this with a little code...
    String s = new String("AA");
    assert s != "AA";
    assert s.equals("AA");
    assert s.intern() == "AA";~

  • String objects

    String s1 = "abc";
    String s2 = "def";is it correct that s1 and s2 are both references to the same object? and therefore this same object has two different values, being "abc" and "def"?
    thanks.

    how can they become all of a sudden different objects
    just cause one of the values change?Have a look at this "drawing":
    // Start JVM
    /*               +----------+
                     |          |
       String-pool:  |          |
                     |          |
                     +----------+
    String s1 = "qwe";
       "qwe" is not in the pool, so it gets created
                     +----------+
                     |        +-+---[s1]
       String-pool:  |        | |
                     |"qwe"<--+ |
                     +----------+
    String s2 = "qwe";
       "qwe" IS in the pool, so it gets 'recycled'
                     +----------+
                     |        +-+---[s1]
       String-pool:  |        | |
                     |"qwe"<--+-+---[s2]
                     +----------+
    s1 = "qaz";
       point s1 to a different String (which is not yet present, so it gets created)
                     +----------+
                     |"qaz"<----+---[s1]
       String-pool:  |          |
                     |"qwe"<----+---[s2]
                     +----------+
    */Note that, as already mentioned by the previous poster, that s1 and s2 are merely references* to String objects.
    * think of them as pointers, as you will (not too loud though!)
    ; )

  • Submit submit a large number of task to a thread pool (more than 10,000)

    i want to submit a large number of task to a thread pool (more than 10,000).
    Since a thread pool take runnable as input i have to create as many objects of Runnable as the number of task, but since the number of task is very large it causes the memory overflow and my application crashes.
    Can you suggest me some way to overcome this problem?

    Ravi_Gupta wrote:
    I have to serve them infinitely depending upon the choice of the user.
    Take a look at my code (code of MyCustomRunnable is already posted)
    public void start(Vector<String> addresses)
    searching = true;What is this for? Is it a kind of comment?
    >
    Vector<MyCustomRunnable> runnables = new Vector<MyCustomRunnable>(1,1);
    for (String address : addresses)
    try
    runnables.addElement(new MyCustomRunnable(address));
    catch (IOException ex)
    ex.printStackTrace();
    }Why does MyCustomRunnable throw an IOException? Why is using up resources when it hasn't started. Why build this vector at all?
    >
    //ThreadPoolExecutor pool = new ThreadPoolExecutor(100,100,50000L,TimeUnit.MILLISECONDS,new LinkedBlockingQueue());
    ExecutorService pool = Executors.newFixedThreadPool(100);You have 100 CPUs wow! I can only assume your operations are blocking on a Socket connection most of the time.
    >
    boolean interrupted = false;
    Vector<Future<String>> futures = new Vector<Future<String>>(1,1);You don't save much by reusing your vector here.
    for(int i=1; !interrupted; i++)You are looping here until the thread is interrupted, why are you doing this? Are you trying to generate loading on a remote server?
    System.out.println("Cycle: " + i);
    for(MyCustomRunnable runnable : runnables)Change the name of you Runnable as it clearly does much more than that. Typically a Runnable is executed once and does not create resources in its constructor nor have a cleanup method.
    futures.addElement((Future<String>) pool.submit(runnable));Again, it unclear why you would use a vector rather than a list here.
    >
    for(Future<String> future : futures)
    try
    future.get();
    catch (InterruptedException ex)
    interrupted = true;If you want this to break the loop put the try/catch outside the loop.
    ex.printStackTrace();
    catch (ExecutionException ex)
    ex.printStackTrace();If you are generating a load test you may want to record this kind of failure. e.g. count them.
    futures.clear();
    try
    Thread.sleep(60000);Why do you sleep even if you have been interrupted? For better timing, you should sleep, before check if you futures have finished.
    catch(InterruptedException e)
    searching = false;again does nothing.
    System.out.println("Thread pool terminated..................");
    //return;remove this comment. its dangerous.
    break;why do you have two way of breaking the loop. why not interrupted = true here.
    searching = false;
    System.out.println("Shut downing pool");
    pool.shutdownNow();
    try
    for(MyCustomRunnable runnable : runnables)
    runnable.close(); //release resources associated with it.
    catch(IOException e)put the try/catch inside the loop. You may want to ignore the exception but if one fails, the rest of the resources won't get cleaned up.
    The above code serve the task infinitely untill it is terminated by user.
    i had created a large number of runnables and future objects and they remain in memory until
    user terminates the operation might be the cause of the memory overflow.It could be the size of the resources each runnable holds. Have you tried increasing your maximum memory? e.g. -Xmx512m

  • A question about string.trim()

    I got a fragment of code as follows:
    String s = "abcd ";
    boolean a = (s.trim()=="abcd");
    boolean b = (s =="abcd ");
    Why a is false, b is true?

    The reason why the below code has true assigned to be is quite easy to explain:
    String s = "abcd";
    String y = "abcd";
    boolean b = (s == y);
    ...The String class has a "Pool" of strings. When you use String literals; the compiler automatically checks if it is in the String pool already and if it exists; a reference to that String is returned; if not a new entry in the pool is added and then you get a reference to that. This is only true for Stirng literals and String created using the intern() method.
    If you compile this code you will see that the strings are not equal:
    public static void main(String args[])
      String s = "abcd";
      String y = args[0];
      boolean b = (s == y);
      System.out.println(b);
    }This is because the "abcd" is in the String pool when your program starts; but because the value "abcd" passed in (is not created in the pool automaticlaly). Therefor they are two different String objects.
    This code block shows that you can add Strings to the pool. The intern() method checks to see if the String is in the pool already and if it is it will return you a reference to it; if not it will create one and then return it.
    public static void main(String args[])
      String s = "abcd ";
      String y = args[0].intern();
      boolean b = (s == y);
      System.out.println(b);
    }- Chris

  • Behaviour of String as reference type

    I tried this simple code to find out how a String behaves. It does not work as you could expect from a reference type. On the other hand the keyword new is leftout but I expect it is used in the background.
    Can anyone explain !
    Thanks.
    class Te {
    public static void main (String arg[]){
         int[] a = new int [1];
         a[0] = 1;
         int[] b = a;
         a[0] = 2;
         System.out.println("a[0]="+a[0]+" b[0]="+b[0]);
         String c = "AA";
         String d = c;
         c = "BB";
         System.out.println("c="+c+" d="+d);
    And the printout is:
    a[0]=2 b[0]=2
    c=BB d=AA

    I I understand it correctly, the line
    c = "BB";is realy
    c = new String("BB");otherwise c and d should have reference to the same
    String.On some level, yes, but in reality...
    If you know C++, it is should be enough just to say that java's references are really pointers - there are also references in C++ but they mean another things.
    So, c = "BB" just assigns the "reference variable" (pointer) c to a new reference of a String object, but the value of the "reference variable" (pointer) d remains the same. So basicallyString c = "AA";
    String d = c;
    c = "BB";is the same thing asint c = 1;
    int d = 2;
    c = 1;Strings in Java have this nice little extra feature... saying that String c = "BB" and String c = new String("BB") are totally different things. You can check this with code like:String a = "xyzzy";
    String b = "xyzzy";
    String c = new String("xyzzy");
    if (a == b) System.out.println("a and b refer to the same object");
    if (a != c) System.out.println("a and c don't refer to the same object");The literal Strings are stored in a literal String pool, so each occurence of "BB" refers to the same object. But new String("BB") creates a whole new String object, different from the literal "BB".

  • String initialization problem

    I know system process the following statement differently:
    String s1="abc";
    String s2="abc";
    String s3=new String("abc");
    but how does system do it? Are s1 and s2 the same string objects after initialization?
    Thank you for your answer in advance.

    Well.... Hashcodes are NOT the same as adresses and
    for strings hashcodes SHOULD be the same for strings
    holding the same data.Exactly. In fact, having the same hashcode does not even imply that two Strings hold the same data - only the opposite is true - If two Strings hold the same data, then their hashcodes must be the same.
    Creating strings using
    String s1 = "aaa";
    is equivalent to
    String s2 = new String("aaa");
    but just a little more readable.Not true - The second approach creates a new String object, whereas the first will create a new object only if an equal one does not already exist in the String pool.
    To test this, try:
    String s1 = "aaa";
    String s2 = "aaa";
    String s3 = new String("aaa");
    String s4 = new String("aaa");
    System.out.println(s1 == s2);
    System.out.println(s2 == s3);
    System.out.println(s3 == s4);

Maybe you are looking for

  • Beige G3 no longer boots at all

    I've been using it for years (obviously), and the other day I was trying to install Tiger on a new 400 GB hard drive, when I forgot I had to restart using XPostFacto. The specs are in the signature; 1 GHz G4 upgrade, 3 hard drives off an ATA/PCI card

  • I can't get into Itunes store

    everytime I enter itunes it says this: their has occured an unknowned error (11222) and sometimes it just says itunes couldnt connect to itunes store: make sure your network connection is active what do I do?

  • Is there any ,to help me?

    hai, can u help me to write this applet i am in sad bzs i cant get an idea about this ,to tabulate a transmitter conversion.it should prompt user for the transmitter type (eg. pressure transmitter or lebel transmitter or flow transmitter,..etc)the un

  • Firewire Audio interface problems in Windows XP

    I am a happy user of boot camp with Windows XP and have up til now not had any problems. I have two firewire devices, one hard drive, one audio interface. The hard drive has both firewire 400 and 800 connectivity and works perfectly using both. But I

  • Quit while loop in event structure

    Hello, I used event structure in my application and I would like to quit a while loop in an event structure when I pressed a control. But I have a problem because I'm in the event. Do you have a solution. Sam. Attachments: Problem.vi ‏34 KB