当前位置: 动力学知识库 > 问答 > 编程问答 >

Operator precedence in Java not according to Java specification

问题描述:

 import java.util.*;

class OperatorPrecedenceExp

{

public static void main(String[] args)

{

int e=10;

sum=++e+e--;//e-- should b evaluated first

System.out.println("sum="+sum);

}

}

The above code prints sum=22. But according to Java specification e-- should be evaluated before ++e. So result should sum=20 instead of sum=22.

网友答案:

When you say e-- should be evaluated first,

sum=++e+e--;//e-- should be evaluated first

you must be incorrect. For one thing e-- doesn't change e until the next statement (that is the post in post-decrement). Next, if you change your code to,

int sum = ++e + --e;
System.out.printf("sum=%d%n", sum);

You will see that first e is pre-incremented then added to a pre-decrement of e (in that order) because the sum is

21

Your expected result (20) can be obtained with

int e = 11;
int sum = --e + e++;
System.out.printf("sum=%d%n", sum);

or

int e = 9;
int sum = ++e + e--;
System.out.printf("sum=%d%n", sum);

I hope that helps.

Edit

Per your Java Tutorials link,

All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.

You can't just skim the table.

分享给朋友:
您可能感兴趣的文章:
随机阅读: