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

Daniele Tsafack
Daniele Tsafack
265 Points

Equality.java challenge on java basics

Could anyone tell what I'm doing wrong?

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

 String thirdExample = "HELLO";
Josh Gold
Josh Gold
12,207 Points

What output are you expecting? What error(s) are you receiving?

Daniele Tsafack
Daniele Tsafack
265 Points

Check if firstExample is equal to secondExample. The outpout expected is "first is equal to second"

1 Answer

Ryan Ruscett
Ryan Ruscett
23,309 Points

Hello,

You are saying if firstExample is equal to secondExample.

There is no need to use the string literal of the secondExample.

if(firstExample.equals("hello")){

There is also no need for the sys.exit for it's a simple program that will terminate on it's own. Using sys.exit would mean that if it's equal, don't even bother with the rest of the code. Just close the entire program. But we don't want that since we have a second if statement to check in part 2. Only use that if you are sure you want to do that. Like saying quite or something.

This checks to see if firstExample is equal to secondExample in two different ways. By uisng == and .equals. I also show you the second part of the example that uses ignorecase.

There are some differences between == and equals for object comparison or functional equality. But as for this stage in the course. Either one will work.

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

OR

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

}

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

Does this help solve your issue? Let me know if I can clarify anything for you.

Daniele Tsafack
Daniele Tsafack
265 Points

Thank you Ryan. My issue is solved

Josh Gold
Josh Gold
12,207 Points

Using String.equals() method compares the actual values. I think that is what is needed in this example.

I think that using == operator compares if both objects are the same object. I don't think that is what we are looking for in this example.