Java一元操作符++详解

废话不多说,直接上代码。

package com.coshaho.learn;

/**
 * 
 * OperatorLearn.java Create on 2016-11-13 下午8:38:15    
 *    
 * 类功能说明: 深入理解++操作符  
 *
 * Copyright: Copyright(c) 2013 
 * Company: COSHAHO
 * @Version 1.0
 * @Author coshaho
 */
public class OperatorLearn 
{
    // 一元操作符,赋值操作符,三目操作符从右向左运算,其他操作符从左向右运算
    // ++x步骤:1.返回x+1;2.执行x = x + 1;
    // x++步骤:1.返回x;2.执行x = x + 1;
    public static void main(String[] args)
    {
         int x = 1;
         // 步骤1. 计算y(默认值0);
         // 步骤2. (x++)返回x值给临时变量c,为1;
         // 步骤3. x = x + 1,x为2;
         // 步骤4. 计算x,x为2;
         // 步骤5. y = 临时变量c + 2 = 1 + 2 = 3.
         int y = (x++) + x;
         System.out.println("x = " + x);
         System.out.println("y = " + y);
         
         x = 1;
         // 步骤1. 计算y(默认值0);
         // 步骤2. (++x)返回x+1值给临时变量c,为2;
         // 步骤3. x = x + 1,x为2;
         // 步骤4. 计算x,x为2;
         // 步骤5. y = 临时变量c + 2 = 2 + 2 = 4.
         y = (++x) + x;
         System.out.println("x = " + x);
         System.out.println("y = " + y);
         
         x = 1;
         // 步骤1. 计算y(默认值0);
         // 步骤2. 计算x,为1;
         // 步骤3. (++x)返回x+1值给临时变量c,为2;
         // 步骤4. x = x + 1,x为2;
         // 步骤5. y = 1 + c = 1 + 2 = 3.
         y = x + (++x);
         System.out.println("x = " + x);
         System.out.println("y = " + y);
         
         x = 1;
         // 步骤1. 计算y(默认值0);
         // 步骤2. 计算x,为1;
         // 步骤3. (x++)返回x值给临时变量c,为1;
         // 步骤4. x = x + 1,x为2;
         // 步骤5. y = 1 + c = 1 + 1 = 2.
         y = x + (x++);
         System.out.println("x = " + x);
         System.out.println("y = " + y);
         
         x = 1;
         // 1.计算x,为1;
         // 2.计算(x++)返回1给临时变量c
         // 3.x = x + 1,为2;
         // 4.计算x = 1 + c = 1 + 1 = 2;
         x += (x++);
         System.out.println("x = " + x);
         
         int[] xx = {1,3};
         int i = 0;
         xx[i++] *= 2;
         System.out.println("xx[0] = " + xx[0] + ", xx[1] = " + xx[1]);
         
         xx = new int[]{1,3};
         i = 0;
         xx[i++] = xx[i++] * 2;
         System.out.println("xx[0] = " + xx[0] + ", xx[1] = " + xx[1]);
         
         /**
          * 输出
          * x = 2
            y = 3
            x = 2
            y = 4
            x = 2
            y = 3
            x = 2
            y = 2
            x = 2
            xx[0] = 2, xx[1] = 3
            xx[0] = 6, xx[1] = 3
          */
    }
}

 

posted @ 2016-11-13 21:16  coshaho  阅读(2148)  评论(0编辑  收藏  举报