Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Beginning Java and the fly likes lowdown on If? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "lowdown on If?" Watch "lowdown on If?" New topic

lowdown on If?

Jasper Vader
Ranch Hand

Joined: Jan 10, 2003
Posts: 284
here's a question that confused me from John Hunt's mock exam. it confused me because i thought an If statement should have a comparison in the parentheses...
Q. 61
Consider the following program:

public class Test {
public static void main (String args []) { boolean a = false;
if (a = true)

What is the result:
A. Program produces no output but terminates correctly.
B. Program does not terminate.
C. Prints out "Hello"
D. Prints out "Goodbye"
Select the most appropriate answer.

turns out the program prints Hello. i guess the key to it is that a is of type Boolean. maybe if it was of type String it would not have worked?
thanks in advance for any elucidation on this matter

giddee up
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
The key is that the assignment operator forms an expression too, e.g.

The last line is a perfectly legal expression assignment, i.e. a= 5 and b= 3 after the execution of the expression has finished.
Back to your example:

The if ( ... ) conditional must be a boolean expression, assignments are expressions, so boolean assignments are boolean expressions, so your example if ( ... ) test turns out to be true, so 'hello' is printed.
kind regards
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
The fact that you were confused is GOOD . That means that you understood that the (a = true) part of the statement was out of whack. That in real life it probably should have been (a == true) or something.
The problem is not that "a" is a boolean or a String. The problem is that the entire statement in the parenthesis must resolve to a boolean. If you SET "a" to true using "a=true", of COURSE the parenthesis is going to resolve to true. All the time.
Jasper Vader
Ranch Hand

Joined: Jan 10, 2003
Posts: 284

Thanks Jos, thanks Cindy! Yes, the assignment was confusing me, but as you have said, assignments are expressions ... and the variable a was of type boolean, so it was a boolean expression that was true.
wouldn't have worked if a was of type String tho eh.
I agree. Here's the link:
subject: lowdown on If?
jQuery in Action, 3rd edition