What is the difference between “text” and new String(“text”)?

后端 未结 12 1122
悲&欢浪女
悲&欢浪女 2020-11-21 04:42

What is the difference between these two following statements?

String s = \"text\";

String s = new String(\"text\");
12条回答
  •  梦谈多话
    2020-11-21 05:20

    Think of "bla" being a magic factory like Strings.createString("bla") (pseudo). The factory holds a pool of all strings yet created this way.

    If it gets invoked, it checks if there is already string in the pool with this value. If true, it returns this string object, hence to strings obtained this way are indeed the same object.

    If not, it creates a new string object internally, saves it in the pool and then returns it. Thus, when the same string value is queried the next time, it returns the same instance.

    Manually creating new String("") overrides this behaviour by bypassing the string literal pool. So equality should always be checked using equals() which compares the character sequence instead of the object reference equality.

提交回复
热议问题