+ 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

5th Feb 2023, 3:14 PM
Kazantsev Alexander
5 Answers
+ 8
Its because there both the same String object in string pool try String name = new String("Alex"); and compare them...
5th Feb 2023, 3:35 PM
D_Stark
D_Stark - avatar
+ 4
Thank you all very much for you quick response. I'm starting to dig into strings, string pool, etc.
5th Feb 2023, 9:04 PM
Kazantsev Alexander
+ 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.
6th Feb 2023, 8:50 AM
Tibor Santa
Tibor Santa - avatar
+ 2
Kazantsev Alexander don't dig too deep into java you will lose your mind 😄
5th Feb 2023, 9:11 PM
D_Stark
D_Stark - avatar