// Used with objects == is for comparing memory addresses. // However, it can lead to surprises when used with Strings. // String literals are treated in special way. // Below each "apple" is represented by the same String object. // This is to save memory. class Equals { public static String f() { return "apple"; } public static String g() { return "app"; } public static void main(String[] args) { System.out.println("apple" == "apple"); // true - same String object at the same memory address System.out.println("apple" == f()); // true - same String object at the same memory address System.out.println("apple" == ("app" + "le")); // true - compiler optimization, '+' evaluated at compile-time. Result: same as above System.out.println("apple" == (g() + "le")); // false - compiler optimization does not happen. // Result: new String object is created for the result of + at different memory address } }