Java运算符优先级
图中,优先级数越小,优先级越大
示例:
public class PriorityTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i =6;
int j=6;
System.out.println(i++%10); //6
System.out.println(i); //7
System.out.println(".......1.......");
System.out.println(j+++10); //16
System.out.println(i++>7?1:0); //0
System.out.println(i); //8
System.out.println("......2........");
System.out.println(i); //8
System.out.println(j); //7
i+=++j; //i=i+(7+1) 即:8+8
System.out.println(i); //16 先++j,再+=
System.out.println(j); //8
System.out.println("......3........");
i+=j++; //i=16+8
System.out.println(i); //24
System.out.println(j); //9
System.out.println("......4........");
int k = 3;
k+=10/2;
System.out.println(k); //8 先10/2 再+=
//k++ /=3; //The left-hand side of an assignment must be a variable 赋值的左侧必须是变量
//System.out.println(k);
System.out.println("......5........");
int n=0;
//n+=n>0?++n:--n; //-1 先n>0?
n+=--n; //n=n+ --n
System.out.println(n); //-1
n=0;
n=n+--n;
System.out.println(n); //-1
System.out.println("......6........");
int m =3;
m = --m+m;
System.out.println(m); //4
m=3;
m = m-- +m;
System.out.println(m); //5
m=3;
m = m+ m--;
System.out.println(m); //6
System.out.println("......7........");
int a =2;
System.out.println(a++); //2
System.out.println(a); //3
System.out.println(++a); //4
System.out.println(a); //4
System.out.println("......8........");
a=2;
System.out.println(- a--); //-2 即-a ,此时a还是2
System.out.println(a); //1
a=2;
System.out.println(- --a); //-1 即-a ,此时a还是2
System.out.println(a); //1
System.out.println("......9........");
a=2;
if(++a == 3) //3 == 3 true
System.out.println(".........aa...");
System.out.println(a); //3
if(a++ == 4) //3 == 4 false
System.out.println(".........aa...");
System.out.println(a); //4
System.out.println("......10........");
i=100;
i+=i-=i*=i/=10;
System.out.println(i); //-800
/*
* 第一步:i*=i 此时 i=100; 即 i1=100*100 = 10000
* 第二步:由第一步得,式子变为:i+=i-=i1/=10 , 计算i1/=10 得: i2 = i1/10 = 1000
* 第三步:由第二步得:式子变为:i+=i-=i2, 计算i+=i得:i = i+i = 100 +100 =200
* 第四步:由第三步得:式子变为:i-=i2,计算得:i=i-i2 = 200 -1000 = -800
*/
}
}
当 m = 3时:
m = --m+m; 结果m=4,即2+2
m=m- - +m; 结果m=5 ,即3+2
由上面可知,++i 是最大的(除优先级1的外)i++是最小的。
混合运算符 +=等优先级排最后,但比i++大