0

I am wondering if

String s = new String("blabla");

is exactly the same as

String s = "blabla";

I think for the first one this constructor of the String class is called:

 public String(char value[]) {
        this.value = Arrays.copyOf(value, value.length);
    }

but not sure if it's the same for the second one.

In other words, what is this "blabla" from Java point of view?

So while using String s = "blabla"; is s a new stance of String class? and if yes which of its constructors is called?

farmcommand2
  • 1,418
  • 1
  • 13
  • 18

1 Answers1

0

Actually as you may already know String is an immutable class which means once it's intialized it can't be changed anymore so this is exactly why there is two why of creating Strings.

  1. String s = "blabla" : Here this String is created and pushed to the String Constant Pool if it's not already exist.
  2. String s = new String("blabla") : However like this a new String is created each time, without checking if it's already exist in the Pool.

Note : that String s = new String("blabla").intern() is equivalent to String s = "blabla" .

Mouad EL Fakir
  • 3,609
  • 2
  • 23
  • 37
  • so if there is nothing in the pool (there are no string created yet) then `String s = "blabla"` creates a new instance? and if so, what is the called constructor? – farmcommand2 Mar 12 '17 at 20:49
  • The constructor being called in this case is `public String(char value[])` to make sure put a break point at this constructor and run the debug mode. – Mouad EL Fakir Mar 12 '17 at 21:03