File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

lowdown on If?

 
Jasper Vader
Ranch Hand
Posts: 284
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
System.out.println("Hello");
Else
System.out.println("Goodbye");
}
}

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
 
Anonymous
Ranch Hand
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
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"
Sheriff
Posts: 8521
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jasper,
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
Posts: 284
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic