this question is from pg 200 Question 12 from K&B book
the ans is C. count = 3 when i first do the question, i get count = 4, the reason being i evaluated this code first, (++count - 2). however the explanation is that it is a short ciruit expression thus, the left-hand side will be evaluated first, since it evaluated to false the right hand expression would not be executed. So my question is this, arent expression in () always evaulated first? or am i mistaken?
Hi, The variable count is equal to 3 before the if expression is evaluated, so the short circuit operator rule that the right hand side is not evaluated holds in this case as well. Please replace the void test() method with:
Running the main will result in: C:\projects\misc>java BoolArray b = true b = false b = true Before If count = 3 After If count = 3
Does this answer your question? Cheers, Gian Franco Casula
In general they are, but when used in combination with &&, || and ?: this is not the case. The Java Language Specification has a very clear section on this. You could check out paragraph 15.7 of the JLS. It's a very short and not so technical explanation.
Joined: Mar 29, 2004
actaully, i do know the short circuit rule, but i mistakenly thought that code in () will always be executed first.... thanks for the replies and explanations, are there any other cases beside short-circuit logical expressions where code in () are not executed first?
the (++i) and (i++) would not get evaluated first. The "j = ..." expression is evaluated left to right. So, in this case, the i++ returns 0, but sets i to 1. The (++i) returns and sets i to 2. The (i++) returns 2 and sets i to 3. This is another case where code in () does not get evaluated first. [ May 08, 2004: Message edited by: Jong Limb ]