will two strings with same content be stored in the same memory location?

前端 未结 9 1154
慢半拍i
慢半拍i 2020-11-27 19:29

This is a question that I got in an interview.

I\'ve two strings defined as

String s1=\"Java\";
String s2=\"Java\";

My question i

9条回答
  •  时光取名叫无心
    2020-11-27 20:00

    When compiler optimizes your string literals, it sees that both s1 and s2 have same value and thus you need only one string object. It's safe because String is immutable in Java.

    String s1="Java";
    String s2="Java";
    System.out.println(s1== s2);
    

    This gives result true because s1 and s2 points to the same object.

    String Pool is the mechanism that all already defined string are stored in some 'pool' and before creating new String object compiler checks if such string is already defined.

提交回复
热议问题