Either the if statement should read (b == true) or another answer choice should be given (does not compile) ------------------ Ted Velkoff
Ted Velkoff
Carl Trusiak
Sheriff
Joined: Jun 13, 2000
Posts: 3340
posted
0
Originally posted by Ted Velkoff: Either the if statement should read (b == true) or another answer choice should be given (does not compile)
Nothing prevents you from doing an assignment or even a making a method call in an if statement. Java processes any call or assignments first so it's actually the same as writing b=true; if(b) { The restriction in java is that assignments or calls must result in a boolean result(and not an integer result)
Yes, Carl, You are correct. The part of the question that surprised me was not that a boolean expressions could be used, but rather that assignment in Java is an expression. In Pascal/Ada/Eiffel, assignment is a statement. I thought that the C idiom of int i = 5; if (i = 0) ... was prohibited in Java by virtue of assignment being a statement. Instead it is prohibited by requiring the AssignmentExpression to have type boolean. Thanks.
Question: (#127)Given this code, what prints? boolean b = false; if (b = true) {System.out.println("yes");}
Answer: "Yes" prints because the expression (b = true) uses the assignment operator =, not the equality operator ==. So b is set to true, and the result is true so the if condition runs the code. I made the following program:
And it compiled fine. When I run it, I see "yes!" So, is the question okay as is?
Ted Velkoff
Greenhorn
Joined: Jun 29, 2000
Posts: 3
posted
0
Originally posted by Paul Wheaton: And it compiled fine. When I run it, I see "yes!" So, is the question okay as is? [/B]
Yes, the question is OK. I was too fast on the trigger to post my question, but learned another thing about Java along the way. Thanks.