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 Delivering the MVP Exceptions

sandro mirijanashvili
sandro mirijanashvili
2,686 Points

boolean isHit = false;

i don't really understand what does it means , why do we write like that in this video ? what does it means that it's false ?

2 Answers

In this case "false" is just a default value. It means the "isHit" variable is declared with this default value. If the bit of code in the "try" block runs without error, this default value will be replaced by the correct value by the "isHit = game.applyGuess(guess);" statement. If the bit in the "try" block throws an error instead, then line in the try block won't run and the isHit variable will keep its default "false" value. The point here is that the isHit variable MUST have a value. Otherwise you can't use it in the return statement at the end of the method. So you declare it with this default value, and then if no exception is thrown the default value will be overwritten.

Arcee Palabrica
Arcee Palabrica
8,100 Points

I used isHit = true; and it works fine.. or is it?

Steven Morimoto
Steven Morimoto
Courses Plus Student 1,836 Points

I was wondering if isHit needs a default value because the return type is a boolean or is it because of something else?

It's not because it's a boolean. It's because you can't use a variable if it's not initialized, the compiler won't allow it.

ray brown
ray brown
3,592 Points

@sandro mirijanashvili I tried an experiment:

boolean isHit; // Not initialize it at all, actually except that exactly same code with Craig's

and it yields an error like this:

./Prompter.java:28: error: variable isHit might not have been initialized
return isHit;
^
1 error