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 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.