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 trialMarcus Pedersen
3,485 Pointshow do I add an if statement to check if firstExample is equal to secondExample?
I am learning Java and I am a bit confused on how I can add an if statement that checks if firstExample is equal to secondExample
// I have imported a java.io.Console for you, it is named console.
String firstExample = "hello";
String secondExample = "hello";
String thirdExample = "HELLO";
if (secondExample = "hello")) {
console.printf("first is equal to second");
}
2 Answers
Jonathan Hermansen
25,935 PointsYou should be aware that the '==' operator compares object references, and not the text itself. So if you later have a string created with the new keyword (another reference) like this:
String secondExample = new String("hello");
and you compare the strings:
firstExample == secondExample
you will get false, e.g. strings are not equal.
So the right way to compare two strings is to use the .equals()-method from the String class itself, like this:
firstExample.equals(secondExample)
this will return true, e.g. strings are equal.
The image below shows how the equals()-method works, and how two strings (s1 and s2) refers to the same object.
Mei Lee
3,339 PointsUse the variable names and == operator in the if statement.
if(firstExample == secondExample) { // do your stuff }