3

I have a very basic question regarding strings in Java..I am not getting the clear explanation any where..
1. When the string is created with new operator, will it be stored only on heap or on both heap and string pool??
2. When I create a string like
s1="123";
s2=s1+"5";
What would happen at the second step??
a. will it put 1235 in the string literal pool??
b.Will it create a new string 5 in the literal pool??

please answer buddies.

Comments
  • 3
    the difference is that
    String s1 = "a"
    String s2 = "a"
    sysout(s1 == s2) // true

    String s1 = new String("a")
    String s2 = new String("a")
    sysout(s1 == s2) // false

    The thing is that without new keyworf the string ia interned and is stored into string intern pool. They can refer to the same object. With a new keyword you are creating an object and storing it into heap.
  • 2
    @ArturS Dude Could you please help me with the second question ??
  • 3
    @senthilrram it should create a new string and put it into the shared pool, not the heap. If you want to make sure that the string is interned, called intern()
  • 0
    @senthilrram
    It will put it into shared pool.
Add Comment