aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question from K&B Book Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question from K&B Book" Watch "Question from K&B Book" New topic

Question from K&B Book

guan di

Joined: Mar 29, 2004
Posts: 4
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?
Gian Franco
Ranch Hand

Joined: Dec 16, 2003
Posts: 977
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[0] = true
b[1] = false
b[2] = true
Before If count = 3
After If count = 3

Does this answer your question?
Gian Franco Casula

"Eppur si muove!"
Shilpi M Ag
Ranch Hand

Joined: May 07, 2004
Posts: 40
I have changed the code a bit:

The first condtion gets excuted.
b[0] = true
b[1] = false
so b[0] && b[1] = false
then b[2] = true
so b[0] && b[1] | b[2] = true
and thus count gets incremented
Shilpi M Ag
Ranch Hand

Joined: May 07, 2004
Posts: 40
In addtion to what i said above:

in this bit of code cince b[0] == false, the compiler does not go ahead
Karel KoboojBot
Ranch Hand

Joined: Apr 09, 2004
Posts: 35
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.
guan di

Joined: Mar 29, 2004
Posts: 4
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?
Jong Limb

Joined: May 08, 2004
Posts: 12
If you have, for example,

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 ]
I agree. Here's the link:
subject: Question from K&B Book