manoj bhide
manoj bhide

Reputation: 51

Why String Pool behaves differently for literals and variables?

When I concat 2 strings with (+) operator using double quotes and compare with other string literal with same value it result as true .. but when I concat 2 string variables and compare gives false ? why this happens ?

As per my knowledge when we concat strings with (+) operator JVM returns new StringBuilder(string...).toString() which creates a new String instance in heap memory and one reference in String pool . if that is true how is it returning true in one scenario and false in other?

1st scenario :

    String string1 = "wel";
    String string2 = "come";
    string1 = string1 + string2; //welcome

    String string3 = "welcome";
    System.out.println(string3 == string1); // this returns false but have same hashcode

2nd scenario :

    String string4 = "wel" + "come";
    String string5 = "wel" + "come";
    System.out.println(string4 == string5); // this returns true

Can someone help me on this ?

Upvotes: 4

Views: 153

Answers (2)

user207421
user207421

Reputation: 310884

As per my knowledge when we concat strings with (+) operator JVM returns new StringBuilder(string...).toString() which creates a new String instance in heap memory

Correct, unless both operands are literals, in which case a single string constant is created at compile time and pooled.

and one reference in String pool.

False. The only things in the String pool are String constants and String.intern() return values.

if that is true

It isn't.

how is it returning true in one scenario and false in other?

Because your premiss is incorrect.

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 121998

Please follow comments.

 string1 = string1 + string2; //StringBuilder(string...).toString() which creates a new instance in heap..

 String string3 = "welcome"; // It is not in heap. 

So string3 == string1 false

  String string4 = "wel" + "come"; //Evaluated at compile time

  String string5 = "wel" + "come"; //Evaluated at compile time and reffering to previous literal

So string4 == string5 is true

Upvotes: 4

Related Questions