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

Android Build an Interactive Story App (Retired) The Model-View-Controller Pattern Adding Custom Constructors

Sri Krishna
Sri Krishna
1,348 Points

Why we are using boolean function i am not clear about that .. please help me ..

In this video a boolean function is used , please someone help me to know about the boolean function, and its usage clearly .. Thanks in advance..

2 Answers

Hello,

A boolean variable can hold one of two values true or false.

It is used widely to direct the line of execution of code depending on the outcomes of comparisons or tests.

Here is a silly example that shows how a boolean can be used to direct the flow of code execution. It may not help; sorry if it doesn't!

The key bit is mealsEatenToday < 3 - this is a comparator that asks "is mealsEatenToday less than 3" - that creates a true/false answer. There are no other outcomes possible. The code then sets the isHungry boolean to true or false depending on the value, as above.

int mealsEatenToday; 
boolean isHungry;

mealsEatenToday = functionToGetMealNumber(); // this just returns a number between 1 and 5.
        // It doesn't matter how it works, this code is fictional

if (mealsEatenToday < 3) {
  isHungry = true;
} else {
  isHungry = false;
}

I'm no teacher, unfortunately. That's the best I can come up with to try to help you out.

A Boolean can hold a true or false value and is often the result of comparing two things;

  • 1 is less than 2 - true
  • 64 is more than 32 - true
  • 16 is more than 32 - false
  • This is a good example - false

I hope that all helps!

Steve.

Sri Krishna
Sri Krishna
1,348 Points

Hi steve, Thank yo so much ... now i understood the purpose of boolean used in a coding ..and its clear.... once again thank u so much ...

No problem - glad it helped!

Steve.