0

Is

String test1 = "something"

just syntactic sugar for

String test2 = new String("something")

and if it is why do the following lines return different results? (I know the difference between using the == operator and the equals() method)

System.out.println(test1 == "something");     // returns true
System.out.println(test2 == "something");     // returns false

Or is there something more?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
es.16
  • 119
  • 1
  • 1
  • 5
  • This question is asked every day. – Wiktor Stribiżew Sep 09 '16 at 09:49
  • Funny, I could not find an exact dupe for this one. – Bathsheba Sep 09 '16 at 09:50
  • 1
    They all get closed and removed anyway. See http://stackoverflow.com/questions/3052442/what-is-the-difference-between-text-and-new-stringtext – Wiktor Stribiżew Sep 09 '16 at 09:51
  • @WiktorStribiżew: well found. – Bathsheba Sep 09 '16 at 09:54
  • Also see http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java ; It's not syntactic sugar. How you a string literal be syntactic sugar for something that requires using a string literal? Also if that was syntactic sugar, any program using a string literal wouldn't run, since `"something"` is syntactic sugar for `new String("something")`, which is syntactic sugar for `new String(new String("something"))` ... which would lead to infinite recursion depth and therefore a StackOverflow. – fabian Sep 09 '16 at 09:57

1 Answers1

0

All string literals will be "interned" as the java files being compiled.

Have a look of this question: Java string intern and literal

Community
  • 1
  • 1
proQuest
  • 26
  • 1