+ 2
Could someone explain why in Java System.out.println(originalName == name) equals true?
class MyClass { public static void main(String[ ] args) { String originalName = "Alex"; String name = "Alex"; System.out.println(originalName == name); // false System.out.println(originalName.equals(name)); // True } } I thought System.out.println(originalName == name); had to be false. Thank you in advance
8 Antworten
+ 8
Its because there both the same String object in string pool try String name = new String("Alex"); and compare them...
+ 4
Thank you all very much for you quick response. I'm starting to dig into strings, string pool, etc.
+ 4
Easy way to remember:
== comparison operator should only be used with primitive types (int, float, char and the like).
To compare objects, including String or boxed numbers such as Integer, Double, etc you must always use the equals method.
+ 2
Kazantsev Alexander don't dig too deep into java you will lose your mind 😄