The output of the following line of code is: Not Done End

boolean notDone = false;
if (notDone = true)
   System.out.print("Not ");
if( notDone = false)
   System.out.print("Done ");
System.out.println("End");

The answer is false but I am having a hard time understanding why. Aren't the if statements setting notDone equal to true which would print Not and then go to the second loop and set notDone equal to false then print out Done and then End since none of the if statemends are comparing notDone to the initial notDone variable. Thanks!

Recommended Answers

All 7 Replies

The output of the following line of code is: Not Done End

Not according to Java. I just copied and executed the code you posted and it outputted Not End, exactly as expected. Have you tried it?

I know the answer is false but why? More specifically how does = operate in this situation?

The = operator sets the variable on the left of it to the value on the right.

hmm yes if statements are normally evaluate to a boolean, every if statement will end up with either evaluating to true or false:

if(1==1) {
} else if(1==2)
//will during runtime be evaluated as
if(true) {
} else if(false) {
}

however in your example you are not evaluating wether notDone is equal to true or false you are setting the value! so i think its because you are not uing the if statement correctly.

remeber
== is for equality/comparsion
= setting a variables contents.

I know but the problem then is that shouldn't "Done" also print out since this code is only setting a variables contents?

An if statement requires a boolean value.
An expression returns its value. I believe the value of an assignment statement is the value of the lefthand variable.

Thanks.
Im reviewing basic java concepts and I know how to code them but when it comes to answering them on a piece of paper I feel as if I am oblivious xD

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.