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

A quick question on booleans.

I'm a little stuck on how booleans work in Java.

In the Welcome Back video in the Java objects course while the instructor was using REPL, it looked like booleans were used to store and create variables. However, I was taught that booleans are used to determine whether something was true or false. This left me very confused.

Help is appreciated!

2 Answers

in addition, you can use methods that return a boolean to store variables as well, like in the repl, when Craig used

someWords.contains("bunch"); that method returns a boolean value. in the repl, it assigned the boolean its own variable, because Craig did not assign one himself.

if you see a method like: public boolean contains(){ //some code to check if it has the word } it will return a boolean variable that contains an either true or false value. so I could say: boolean hasWord = someString.contains("word"); and the hasWord variable will store that true or false return value.

this especially comes in handy if you want that variable to change at a specific time in your program. for example: If I was making a java program that was a blackjack simulator, and only wanted the player to be able to hit after the dealer had already dealt the cards.

In the beginning of my program I could say: boolean hasDealt = false; if (hasDealt=false){ //dont allow player to hit }else{ hit(); }

but in my deal method I would set the hasDealt variable to true, allowing the program to continue.

Sorry for my extremely verbose explanation.

tl;dr: Yes the boolean determines a true or false but it is also a primitive data type like int and double as stated above, allowing you to store and change these values throughout your program at your will.

Thanks!

Hi Diego,

"boolean" is a data type like "int" or "double". You can create variables of the boolean data type, and those variables will have either true or false values. (Or 1 or 0).