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

Stuart Keenan
Stuart Keenan
3,131 Points

The trues and falses of booleans

I am a bit confused on booleans and how to use them. I understand what a boolean is, providing feedback in a true or false state. The issue for me might be with setting what is true and what is false. In this particular video "storing Guesses" we create this:

  public boolean applyGuess(char letter) {
    boolean isHit = mAnswer.indexOf(letter) >= 0;
    if (isHit) {
      mHits += letter;
      } else {
        mMisses += letter;
    }
    return isHit;
  }

The first boolean applyGuess is going to be defined by the boolean isHit, right? (booleans in booleans) It makes sense to me when we define both the true and false, whether by using an else statement or a " ! " to invoke the inverse. Why are booleans created that sometimes only have one return like the applyGuess boolean above? Hopefully someone will understand my question, as I do not think I am able to explain it well, I just know when booleans are involved I have tendency to get stumped. Thanks for any help!

1 Answer

Per Karlsson
Per Karlsson
12,683 Points

applyGuess isn't a boolean per se. It's a method where you've declared it's return value to be a boolean value. So it can only ever be true or false. At the end of the method you return the value of isHit which is defined inside the method.

An example of use for this method could be something like.

if (applyGuess("H")) {
  system.out.println("You hit it");
} else {
  system.out.println("Bummer, try again!");
}

Don't know if this answers your question.

Stuart Keenan
Stuart Keenan
3,131 Points

Sorry, that is my being new to this and still learning how to talk in Java. I do understand what you are saying in that applyGuess itself is not a boolean only that it's return value is a boolean. I think I am going to keep moving forward and hope that I better learn what it is that is stumping me. Thanks for the help though!