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 trial
Erlend Birketvedt
1,217 PointsWhy can't I use: if (firstExample = (secondExample)) on the first task?
Hi,
I had to use the forums to solve this, and I have solved it now, but when I tried to do it myself, I wrote this code:
// I have imported a java.io.Console for you, it is named console. String firstExample = "hello"; String secondExample = "hello"; String thirdExample = "HELLO"; if (firstExample = secondExample) { console.printf("first is equal to second"); }
That was clearly wrong, but can someone explain to me the difference between equals and =?
2 Answers
Ken Alger
Treehouse TeacherErlend;
Welcome to Treehouse!
In Java == is a reference comparison, i.e. both objects point to the same memory location. equals() evaluates to the comparison of values in the objects. That is a rather simplified overview of it, but in general equals() is the better option when comparing string objects.
Happy coding,
Ken
Erlend Birketvedt
1,217 PointsThank you very much, just what I was looking for
Erlend Birketvedt
1,217 PointsAhh, but of course. Could I have used ==?
Brian Pedigo
26,786 PointsBrian Pedigo
26,786 PointsA single equal sign actually sets the variable, it doesn't check for equality.