sumit goyal
sumit goyal

Reputation: 55

String Object creation without using new keyword

I was studying Strings in Java can anyone tell me if we write

String s = "deepak";

will this create an object in string constant pool or not because we are not using new keyword here so according to me object will not be created?

Upvotes: 0

Views: 97

Answers (1)

Amongalen
Amongalen

Reputation: 3131

String s = "deepak"; will try to reuse a String. If it already exists in the String pool then that object will be used. If it doesn't exists, obviously a new object will be created.

String s = new String("deepak"); will always create a new String which won't be added to the String pool.

A simple test to confirm it (reminder: == compares object references):

public static void main(String args[]) {
    String a = new String("test");
    String b = new String("test");
    String c = "test";
    String d = "test";

    System.out.println(a == b);
    System.out.println(b == c);
    System.out.println(c == d);
}

Output:

false
false
true

In case if you want to read more about this mechanism, it is called String Interning.

Upvotes: 2

Related Questions