Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJassim Alhatem
20,883 PointsWhy 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
jb30
44,806 PointsThe ==
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.