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

Java Java Basics Perfecting the Prototype String Equality

not sure what is wrong in this answer. It says the "=" can not be boolean language. if (firstExample = "hello"); console

the question was: add an if statement and print out.... this was my answer if (firstExample = "hello"); console.printf("first is equal to second");

it says there's only one error ponting to the "="

Equality.java
// I have imported a java.io.Console for you, it is named console. 
String firstExample = "hello"; if (firstExample = "hello"); console.printf("first is equal to second");
String secondExample = "hello";
String thirdExample = "HELLO";

3 Answers

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

Amanda;

Welcome to Treehouse!

In Java, and many other languages, there is a difference between a single equal sign, and two or three consecutive equal signs. One equal sign is an assignment operator, it assigns a value of something to something else.

String name = "Amanda";

That assigns the string value Amanda to the variable name.

Two equal signs together, == is a relational operator (equal to) which evaluates whether two things are equal.

if (name == "Amanda") {
    System.out.println("Hello!");
}

In your code, you should be using the double equal sign... or better yet the .equals() method. :wink:

Happy coding,
Ken

Hi there,

Just one point on the above answers; we shouldn't really use == to check for string equality.

The reasons are covered in Craig Dennis's course, The Thing About Strings and are also explained better than I'm able to in this post on S.O.. There's another TH thread here too.

While you can probably get through a challenge using ==, it is better to use the .equals() method to check for logical equality, rather than testing for the two things being the same in memory.

It's a small point, but one worth making as it is certainly best practice. The course video covers the equals() method just before the 2 minute point.

Steve.

Adam Pengh
Adam Pengh
29,881 Points

You're trying to compare the two variables and their values. You do that with a conditional statement like so:

if(firstExample == secondExample) {
  console.printf("first is equal to second");
}