What is the difference between == and equals() in Java?
Hello colleagues! I just started learning Java and encountered a confusing situation when comparing strings. I wrote a simple code:\n\n```java\nString a = "Hello";\nString b = "Hello";\nString c = new String("Hello");\n\nSystem.out.println(a == b); // true\nSystem.out.println(a == c); // false\nSystem.out.println(a.equals(c)); // true\n```\n\nWhy does `a == b` return `true`, but `a == c` return `false`? And what does `equals()` have to do with it? I thought both operators compare values. What's the catch? Please explain, as a beginner, when to use `==` and when to use `equals()`. I'm especially interested in how this works with strings and other objects.
No answers yet.
Log in to leave an answer