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

I dont understand how 'if(isHit == true){ hits += letter; } why is it not just hit = letter?

public boolean applyGuess(char letter){

boolean isHit = answer.indexOf(letter) != -1;
if (isHit == true) {
  hits += letter;
} else {
  misses += letter;
}
return isHit;

i understand you have to add the letter to hits but I'm not sure how += is performing this

1 Answer

andren
andren
28,558 Points

The += operator is a shorthand that sets the variable on the left equal to itself + whatever is on the right. In other words

hits += letter;

Is the same as:

hits = hits + letter;

Or put a bit more simply it is a fast way of adding something to a variable. If you used the = operator instead then you would replace whatever was stored in the variable with the new value, rather than adding to the existing value.