This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I'm guessing you're asking this from reading about Strings, so I'll answer in the same context: The constant pool is created at compile time and the values in it are incorporated in the resulting class file. Values that get included in the pool are things that you hard-code, e.g. string literals like "Hello, world." A value will appear only once in the constant pool, so even if you have the same value hard-coded into your program in several different places, you will have only one copy of that value in memory. The heap is where objects exist at runtime. Every "new" statement in your program adds an object to the heap. So, the code: String s1 = new String("foo"); String s2 = new String("foo"); results in 1 String in the constant pool ("foo") and two Strings on the heap (s1 & s2). Junilu
Junilu, You Wrote: String s1 = new String("foo"); String s2 = new String("foo"); results in 1 String in the constant pool ("foo") and two Strings on the heap (s1 & s2). Would it results in one string in constant pool i.e; foo? I don't think so because when you are making object through new operator it will not copy that string in pool as well. Corect me if I am wrong. Thanks Asif Masood
Hi all, String s1 = new String("foo"); String s2 = new String("foo"); These statements create two String objects in the heap both of which contain the unicode characters for the word "foo". 's1' and 's2' are reference type variables. They are not objects. String s1 = "foo"; String s2 = "foo"; The above creates one String object in the constant-pool; "foo" and two reference type variables that both hold the memory address for the same "foo" string object. String literals use the pool; Strings calculated at runtime ie using new or '+' are set at compile time. Primitive variables ie boolean, int, long, etc are stored in their own area of memory and have pre-defined sizes which are known at compile-time. The size of an object cannot be known precisely at runtime, so a reference type variable is used. A reference type variable stores the memory address for an oject in memory. A memory address is a set size ie 16-bit, 32-bit or 64-bit ... the compiler always knows how much memory it requires to hold it. Hope that helps. ------------------ Jane Griscti Sun Certified Programmer for the Java� 2 Platform [This message has been edited by Jane Griscti (edited April 30, 2001).]