位置:首页 > Java技术 > Java基础教程 > Java赋值运算符示例

Java赋值运算符示例

下面的简单示例程序演示了赋值运算符。复制并粘贴下面的Java程序于Test.java文件,并编译和运行这个程序:

public class Test {

  public static void main(String args[]) {
     int a = 10;	
     int b = 20;
     int c = 0;

     c = a + b;
     System.out.println("c = a + b = " + c );

     c += a ;
     System.out.println("c += a  = " + c );

     c -= a ;
     System.out.println("c -= a = " + c );

     c *= a ;
     System.out.println("c *= a = " + c );

     a = 10;
     c = 15;
     c /= a ;
     System.out.println("c /= a = " + c );

     a = 10;
     c = 15;
     c %= a ;
     System.out.println("c %= a  = " + c );

     c <<= 2 ;
     System.out.println("c <<= 2 = " + c );

     c >>= 2 ;
     System.out.println("c >>= 2 = " + c );

     c >>= 2 ;
     System.out.println("c >>= a = " + c );

     c &= a ;
     System.out.println("c &= 2  = " + c );
  
     c ^= a ;
     System.out.println("c ^= a   = " + c );

     c |= a ;
     System.out.println("c |= a   = " + c );
  }
} 

这将产生以下结果:

c = a + b = 30
c += a  = 40
c -= a = 30
c *= a = 300
c /= a = 1
c %= a  = 5
c <<= 2 = 20
c >>= 2 = 5
c >>= 2 = 1
c &= a  = 0
c ^= a   = 10
c |= a   = 10