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

Meenakshi Bohra
Meenakshi Bohra
1,182 Points

Add an if statement that checks to see if firstExample is equal to secondExample. If it is, print out "first is equal to

Add an if statement that checks to see if firstExample is equal to secondExample. If it is, print out "first is equal to second".

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

}

String firstExample = "hello";
String secondExample = "hello";
String thirdExample = "HELLO";

2 Answers

Ryan Ruscett
Ryan Ruscett
23,309 Points

Hello,

First thing is first. The variable declarations should go at the top. A best practice we will call here.

String firstExample = "hello";
String secondExample = "hello";
String thirdExample = "HELLO";

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

}

Now, the .equals is going to compare two objects. You had "secondExample" in quotes. This is handling it as a String Literal. Which isn't what it's looking for.

If you remove the quotes from secondExample. The code will work.

Does this make sense? Let me know if not and I can explain further.

Thanks!

Meenakshi Bohra
Meenakshi Bohra
1,182 Points

Add an if statement that checks to see if firstExample is equal to secondExample. If it is, print out "first is equal to second"

Ryan Ruscett
Ryan Ruscett
23,309 Points

Not sure I follow you.

Yes firstExample is really "hello" and secondExample is really "hello". So they are equal. But firstExample which is really "hello" is not equal to "secondExample". secondExample and firstExample are references to data. They are not the actual data. but when you put secondExample in quotes. It's thinking that's the actual data. Which in that case you don't use .equals but == instead.

Are you still confused on something?

Meenakshi Bohra
Meenakshi Bohra
1,182 Points

if (firstExample.equalsIgnoreCase(thirdExample)) { console.printf("first and third are the same ignoring case"); )

Ryan Ruscett
Ryan Ruscett
23,309 Points
if (firstExample.equalsIgnoreCase(thirdExample)) { 
  console.printf("first and third are the same ignoring case");
} <------------------------------------------------------------------YOU HAVE ) YOU NEED }