Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Basics Perfecting the Prototype String Equality

how do I add an if statement to check if firstExample is equal to secondExample?

I am learning Java and I am a bit confused on how I can add an if statement that checks if firstExample is equal to secondExample

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 (secondExample = "hello")) {
  console.printf("first is equal to second");
}

2 Answers

You should be aware that the '==' operator compares object references, and not the text itself. So if you later have a string created with the new keyword (another reference) like this:

String secondExample = new String("hello");

and you compare the strings:

firstExample == secondExample

you will get false, e.g. strings are not equal.

So the right way to compare two strings is to use the .equals()-method from the String class itself, like this:

firstExample.equals(secondExample)

this will return true, e.g. strings are equal.

The image below shows how the equals()-method works, and how two strings (s1 and s2) refers to the same object.

comparing strings

Use the variable names and == operator in the if statement.

if(firstExample == secondExample) { // do your stuff }