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
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
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
Joined: Jan 10, 2003
Posts: 284
posted
0
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.