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

code challenge

how do you compare the two string in the same if statement

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

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

2 Answers

In Java Strings are objects so to compare them you have to use

string1.equals(string2)

This is true when comparing two objects of compatible types.

Dan Johnson
Dan Johnson
40,533 Points

"equalsIgnoreCase" is a method of the String class. You can call it like any other method:

firstExample.equalsIgnoreCase(thirdExample)

As James mentions you'll want to use the "equals" method when comparing the contents of the Strings. The == operator checks if two references are identical, in that they both refer to the same object in memory.