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

Ariel Espinal
Ariel Espinal
5,451 Points

Why use string methods instead of strings themselves? - (Java)

I just finished the string methods portion of the course, and one of the quizzes made me think...

The question was, Write an if statement that will compare 2 strings to see if they are the same.

//String blahBlah = "hello";

//String blahBlah2 = "hello";

My original answer was this...

if (blahBlah == blahBlah2)

{ console.printf("These 2 are the same."); }

Which I found out was wrong.

I figured it out already using the string method .equals, but why was my first answer wrong though? aren't these variables already declared as strings already?

1 Answer

It's complicated.

Basically, using the == operator in Java doesn't work at all like it does in other languages. When you use the == operator in Java, it doesn't look at the value of each side. Rather, it looks at the reference.

So, if you create two separate strings that hold the same value and store them in variables, and then try to compare the two with ==, it returns false, because the two objects are different objects, stored in different places of your computer's memory. Even though they hold the same value, they're two completely different objects to your computer.

If, however, you were to compare the literals directly, like this:

if ("hello world" == "hello world") {
    // your code here...
}

...then it would return true, because the literals are the exact same thing, as they haven't been stored in memory.

Like I said, it's complicated. Maybe this Stack Overflow post will help.