From: Ryan Chan on
Hi, some simple question about the Operator precedence



int i = 9;
System.out.println(i++ + 2);

Why it print 11 instead of 12, assume operator is evaluated from left
to right?

From: Lew on
On 05/08/2010 09:48 AM, Ryan Chan wrote:
> int i = 9;
> System.out.println(i++ + 2);
>
> Why it print 11 instead of 12, assume operator is evaluated from left
> to right?

What is the definition of postincrement?

To put another way, given:

int i = 9;
int j = i++;

what is the value of j?

It has nothing to do with precedence.

--
Lew
From: markspace on
Ryan Chan wrote:
> Hi, some simple question about the Operator precedence
>
>
>
> int i = 9;
> System.out.println(i++ + 2);
>
> Why it print 11 instead of 12, assume operator is evaluated from left
> to right?
>


Yeah, it's POST increment. That means i is incremented AFTER it's value
(9) is used. Not a precedence issue. PEBCAK issue.

From: Lew on
Ryan Chan wrote:
>> int i = 9;
>> System.out.println(i++ + 2);
>>
>> Why it print 11 instead of 12, assume operator is evaluated from left
>> to right?

markspace wrote:
> Yeah, it's POST increment. That means i is incremented AFTER it's value
> (9) is used. Not a precedence issue. PEBCAK issue.

OP: Consider reading the documentation.

The Java tutorial explains this sort of thing nicely:
<http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op1.html>
and, of course, the Java Language Specification is the authority on the matter:
<http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#292383>

And there's no need to assume the order of evaluation; it's specified by the
language's rules.

--
Lew
From: EJP on
On 8/05/2010 11:48 PM, Ryan Chan wrote:
> Why it print 11 instead of 12, assume operator is evaluated from left
> to right?

Apart from what the other respondents have said, operators are not
evaluated left to right. Neither are operands other than those around a
single binary operator.
 |  Next  |  Last
Pages: 1 2 3
Prev: Business Calendar
Next: Reading from very large file