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 Harnessing the Power of Objects Incrementing and Decrementing

Ivar-Endrik Eiche
Ivar-Endrik Eiche
4,582 Points

Why is it necessary to define default variable wasDispensed=false?

If all we need is to empty the dispenser, why we need to declare that wasDispensed equals false? Or in other words, how the default variable is useful?

Ivar-Endrik Eiche
Ivar-Endrik Eiche
4,582 Points

My code:

public boolean dispense() {
    boolean wasDispensed=false;
    if (!isEmpty()) {
        pezCount--;
        wasDispensed=true;
    }
      return wasDispensed;
  } 

1 Answer

Let look at this code where I removed the =false.

public boolean dispense() { boolean wasDispensed; if (!isEmpty()) { pezCount--; wasDispensed=true; } return wasDispensed; }

let say the if condition in (!isEmpty()) is not true, then you will go straight to the

return wasDispensed;

but wasDispensed is not initialized ... so it is falsy by default .... and you should get back a false; Right?

not exactly, the Java compiler likes to help you ... and frankly tries to stop you from passing around un-initialized values.

if I was writing this code in Javascript or Python, I'll probably get away with it. In Java and if I recall correctly, C# it won't work

Back to your question "Or in other words, how the default variable is useful?":

default values comes handy when you create objects from classes. Attributes in objects will retain their default values, unless otherwise assigned.

Hope this helps. If this answers your question, please mark the question as answered.