aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Operator precedence Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Operator precedence" Watch "Operator precedence" New topic
Author

Operator precedence

chinu sharma
Greenhorn

Joined: Jun 15, 2003
Posts: 1
int k = 1;
int i = +k + k++
On running, the value of i is 2.
((+k) + (k++))
( 1 + 1 )
I can understand this assuming that unary + and postfix operators have the same precedence.
But, according to JLS the postfix operator has higher precedence compared to unary +, so that k++ should be evaluated first and then +k.
((+k) + (k++))
( 2 + 1 )
According to this, answer is 3.
Please explain, why the compiler is not following the precedence given in the JLS.
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
When expressions with multiple operands are evaluated, they are generally evaluated from left to right. From the JLS, §15.7.1 Evaluate Left-Hand Operand First:

The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.

Be sure to check out that section of the JLS as I feel it will answer your questions.
I hope that helps,
Corey


SCJP Tipline, etc.
Brian Joseph
Ranch Hand

Joined: May 16, 2003
Posts: 160
I was evaluating expressions the same way, and when writing code I'd always use parens like any sane person.
But the compiler doesn't evaluate expressions that way. You have the right technique with replacing all the variables with values as a first step.
But the rule you have to follow is this: Evaulate left to right, and respect predecence.
Try this:
i = k++ + k; Now you get 3.
1 (2) + 2 = 3
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
These discussions might alos help:
http://www.coderanch.com/t/190825/java-programmer-SCJP/certification/Array
http://www.coderanch.com/t/239576/java-programmer-SCJP/certification/result


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
 
 
subject: Operator precedence