0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.