What is the difference between == and equals() in Java?

For primitives, == compares the values. For objects, == checks if both variables point to the same object. The equals() method checks if the content is the same (if the class overrides it, like String does).

public class Main {
    public static void main(String[] args) {
        String a = "java";
        String b = "java";
        String c = new String("java");

        System.out.println(a == b);        // same object in the string pool
        System.out.println(a == c);        // different objects
        System.out.println(a.equals(c));   // same text
        System.out.println(5 == 5);
    }
}
Output

true
false
true
true

See Java Strings.


Learn more about the similar topics:
Tutorials
Java Strings
Java String Methods
Java StringBuilder and Text Blocks
Exercises & Assignments
Reverse a string
Check if a string is a palindrome
Count the vowels in a string
Interview Questions & Answers
What is the difference between == and equals() in Java?
Why is String immutable in Java?
What is the difference between String, StringBuilder and StringBuffer?
What is the string pool in Java and what does intern() do?