0
class Demo {
    public static void main(String[] args) {
        String a=new String("data");
        String b="data";
        if(a==b)                             // return false
            System.out.println("a and b has same reference address");
        else
            System.out.println("not same");

In case of new keyword object, does "data" is actually store in Stringconstant pool .if it is stored then variable a and b both have same reference address and return true, if not then false.

String c=new String("data").intern();
String d="data";
if(c==d)
    System.out.println("true");
else
    System.out.println("false");
   }
}

And also if we use intern() method both variable have same reference address,that mean intern() method is use to store String in String Constant pool. I'm little bit confused , anyone help

  • "that mean intern() method is use to store String in String Constant pool" not quite. `intern()` will store string in pool only if pool didn't have such string already. If it did, `intern()` would return reference to already store object (in your case `"data"` literal which was used as *argument* of `new String("data")`). – Pshemo Sep 11 '17 at 19:14

1 Answers1

0

True.

But there's more than one object used in you code.

new creates an object every time it is called - that's Java semantics and it cannot be worked around (e.g. someone might want to synchronize on the freshly created object), and String literal (i.e. just letters in quotes) creates an object while class is first loaded.

When you write in a method:

new String("test");

Then one string string gets created in the pool while the class is loaded and another one will be created each time the line is called (maybe never, maybe many times). Since strings are immutable, the second string might share the char buffer with the first one, so usually it's not a problem in terms of memory used.

fdreger
  • 12,264
  • 1
  • 36
  • 42