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

Jacob Zimny
Jacob Zimny
2,032 Points

"Am I sure I used the 'equals' method and 'printf' function?"

I am getting an error like this from the site (not the code) for the quiz. Here is my answer. I have looked over it and the video several times and cannot find the error the site is looking for:

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

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

1 Answer

Hi, you should declare the secondExample and thirdExample before the If Statement. The compile reads the code from the top to the bottom. And when he tries the if Statement he doesn't "know" the secondExample because he didn't "read" it. He has to "read" it before the if statement to "know" it...just remember computers are stupid and you have to tell them everything ;)

You have to declare it before the if statement to make a valid condition. Also your if Statement should look like this:

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

You need the secondExmaple as condition. When you use the "" you actuall test if the String fistExampe looks like this: "secondExample". But thats wrong because you want to test if the two variables are equal and not if the variable firstExample is "secondExample". Man that quiet diffucult to explain for someone who does not speak english all day :) Here this code should work

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

Hm Syntax Highlighting somehow does not work :(

Jacob Zimny
Jacob Zimny
2,032 Points

That was outstanding. Thank you so much!