jQuery in Action, 2nd edition
The moose likes Ranch Office and the fly likes Bug in Roundup Q. 127 Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » This Site » Ranch Office
Reply Bookmark "Bug in Roundup Q. 127" Watch "Bug in Roundup Q. 127" New topic
Author

Bug in Roundup Q. 127

Ted Velkoff
Greenhorn

Joined: Jun 29, 2000
Posts: 3
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
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)


I Hope This Helps
Carl Trusiak, SCJP2, SCWCD
Ted Velkoff
Greenhorn

Joined: Jun 29, 2000
Posts: 3
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

Joined: Dec 14, 1998
Posts: 17883

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

Joined: Dec 14, 1998
Posts: 17883

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
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.
 
 
subject: Bug in Roundup Q. 127
 
MyEclipse, The Clear Choice