What is the difference between these two following statements?
String s = \"text\";
String s = new String(\"text\");
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.