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 Incrementing and Decrementing

Anas Rida
Anas Rida
8,183 Points

use same if statement twice

How is it that we are able to use the "if (dispenser.isEmpty())" twice with different outcomes? In our case how did the program know which line to print???

2 Answers

Kourosh Raeen
Kourosh Raeen
23,732 Points

I'm not sure what you mean by different outcomes. Are you referring to the two different statements that are printed?

Anas Rida
Anas Rida
8,183 Points

yes, the two different strings that are printed

Kourosh Raeen
Kourosh Raeen
23,732 Points

You can have as many as those if statements as you want and java goes through the in order and prints whatever string you want to print as long as the if condition is true. The first one is this:

if (dispenser.isEmpty()) {
    System.out.println("The Dispenser is empty");
}

At this point in the program the dispenser is empty so dispenser.isEmpty() return true. Since the if condition is true we see the string "The Dispenser is empty" printed on screen.

Next one is:

if (!dispenser.isEmpty()) {
    System.out.println("It is no longer empty");
}

This one is coming after we've loaded the dispenser so dispenser.isEmpty() return false but the negation operator ! turns that into true. The if condition is true so the string "It is no longer empty" gets printed.

Last one is:

if (dispenser.isEmpty()) { 
    System.out.println("You ate all the pez");
}

This one is coming after the while loop that keeps dispensing pez until we run out. So by the time we get to this if statement the dispenser is empty, similar to the first if statement, therefore the loop condition is true and the string "You ate all the pez" gets printed.

Hope this helps.