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) Harnessing the Power of Objects Method Signatures

Adam Brown
Adam Brown
1,893 Points

Why does while (dispenser.dispense()) { System.out.println("Chomp!"); } actually cause the dispenser to dispense?

My understanding of while() is that it is stating while "this" is true, this will happen. I don't understand how this line of code actually will make pez dispense. I would understand if it were something like while(mPezCount>0){dispenser.dispense();}, but just don't see how putting something in the while parentheses calls for an action to take place. Does it have something to do with it being a boolean statement?

1 Answer

Christopher Augg
Christopher Augg
21,223 Points


Yes, it does have to do with it being a boolean statement. The dispense() method can be called like this as long as it returns a boolean.

The dispense method returns a boolean.

       public static boolean despense() {

        //initializes to false
         boolean wasDispensed = false; 

        //calls isEmpty() to make sure it is not empty using !
        if(!isEmpty()) {
            // Only decrements if mPezCount is not empty
            // Only assigns true if mPezCount is not empty. 
            wasDispensed = true; 
        // Returns false if mPezCount is empty. Returns true if mPezCount is not empty.
        return wasDispensed;

         // On each iteration- if dispense() returns true (not empty), execute inner block.
         //                    if dispense() returns false(is empty), break out of while loop. 
         while (dispenser.dispense()) { 

Basically, the while statement reads : I will continuously call the dispense() method and execute the code within its block as long as the Pez dispenser is not empty.

I hope this helps.