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 Objects Creating the MVP Storing Guesses

Tetsuya Uno
Tetsuya Uno
21,024 Points

What is the meaning of "boolean isHit = answer.indexOf(letter) != -1;"?

I understand that this declares a variable of "isHit", but why can he use !=-1 right after the declaration? Is this a shortcut?

Does this return true if isHit is not -1 and false if it is?

1 Answer

michaelcodes
michaelcodes
5,604 Points

Hi there! so for the line of code:

boolean isHit = answer.indexOf(letter) != -1;

You are correct that isHit will become true if answer is NOT equal to -1, and false if it is equal to -1. The first equal sign will be assigning isHit with the boolean value that is returned from the expression:

answer.indexOf(letter) != -1;

the "!=" is the operator to check for Inequality between 2 things. In this case we want to check whether our answer contains the "letter". If it does, then it will return some index number that is zero or greater. In that case, the value is not -1, and therefore we return a true value. If it doesn't contain the letter, it will always return -1, which means there is no index that contains the letter location, and will always return -1. This sets our isHit to false.

I know this explanation may be kind of confusing, if you have any additional questions just let me know!

Take care and happy coding :)

Tetsuya Uno
Tetsuya Uno
21,024 Points

Thank you for the answer. Understood completely!