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

How to compare two strings whilst ignoring casing

I am currently stuck at a task 2 challenge asking me to add an if statement to check and compare 2 string variables whilst ignoring casing. If true, an output to the user should read ''first and third are the same ignoring case''

Please look at the last line in the code as this is where my error is. Not sure what I am doing wrong here but your help will be highly appreciated.

Thank you :)

Equality.java
// 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("Frist is equal to second");}

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

When comparing Strings for equality do you want to use == or .equals() ?
Google this and find a good StackOverflow answer, its a really important concept and will give you good insight into a lot about references.

Remember you dont need to retype the strings in your if statements, you already have a variable name for them right?

2 Answers

Your code : if (firstExample == secondExample)

compares the memory reference not the actual value/content of the string. If you want to compare the actual strings for the same value you need to use .equals(). As I understand you always want to use .equals() when comparing strings.
I would suggest using if(firstExample.equals(secondExample)).

Your code : if (firstExample == thirdExample.equalsIgnoreCase("hello"))

Here we dont want to pass a new string to the equalsIgnoreCase method, just pass the the variable name for comparison. Again, dont use == with strings. You want something like if(firstExample.equalsIgnoreCase(thirdExample)).

aahh.. orite! I see what you mean now, I was using the incorrect syntax to solve the problem in the first place. Thanks for the suggestion, It managed to make the program work now and I understand where I Went Wrong.

Thanks for your help.

Still not sure what I have done wrong. I have checked stack overflow for this but I cannot figure out

No problem, happy coding!