Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Bug in Roundup Q. 127  RSS feed

 
Ted Velkoff
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Either the if statement should read (b == true)
or another answer choice should be given (does not compile)
------------------
Ted Velkoff
 
Carl Trusiak
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)

 
Ted Velkoff
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

------------------
Ted Velkoff
 
paul wheaton
Trailboss
Posts: 22526
Firefox Browser IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tony, if you use your ftp access, you can find the file that has the actual question in it and post it here so we can know what we are discussing.
 
paul wheaton
Trailboss
Posts: 22526
Firefox Browser IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!