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

前端 未结 9 1162
慢半拍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:08

    When you have

    String str1 = new String("BlaBla");  //In the heap!
    String str2 = new String("BlaBla");  //In the heap!
    

    then you're explicitly creating a String object through new operator (and constructor). In this case you'll have each object pointing to a different storage location.

    But if you have:

    String str1 = "BlaBla";        
    String str2 = "BlaBla";
    

    then you've implicit construction. Two strings literals share the same storage if they have the same values, this is because Java conserves the storage of the same strings! (Strings that have the same value)

提交回复
热议问题