Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java

Jassim Al-Hatem
Jassim Al-Hatem
20,639 Points

Why does '==' return false but '.equals()' returns true with the same given values.

public class test {
    public static void main(String[] args){

        String text = "Good luck everyone";

        text = text.toUpperCase();

        int find_index = text.indexOf("LUCK");
        int find_space = text.indexOf(" ", find_index);

        String find_word = text.substring(find_index, find_space);

        System.out.println("LUCK is in text: " + (find_word.equals("LUCK"))); // returns true
        System.out.println("LUCK is in text: " + (find_word == "LUCK"); // returns false

    }
}

1 Answer

The == operator compares the address of the strings in memory and the .equals method compares the content of the strings.

The == operator is used for primitive types, such as int and char. The .equals method is used for objects.