zoukankan      html  css  js  c++  java
  • Java 基础知识总结 (三、运算符)

    三、Operators 运算符

      Assignment Operators(赋值运算符)

      =   +=   -=   %=   *=   /=    <<=     >>=     >>>=    &=    ^=      |=

    public class ByteDemo {
        public static void main(String[] args) {
            byte b1=2;
            byte b2=3;
            b1=(byte)(b1+b2);  //加法,转int
            b1+=b2;            //赋值,不转int
        }
    }
    

      b1+=b2;与b1=b1+b2;是否完全等价?

      答案是否定的。byte类型参数与运算时要先转换为int型,因此要进行强制类型转换。(可以把“b11+=b2;”看做是对“b1=(byte)(b1+b2);”的优化!)

      Comparison Operators(比较运算符)

      >    >=     <     <=     instanceof

      Equality Operators(相同运算符)

      ==  !=

      Arithmetic Operators(算术运算符)

      +       -       *       /        %

      Shift Operators(移位运算符)

      >>   <<    >>>

    public class Test {
    	public static void main(String[] args) {
    		String s1 = Integer.toBinaryString(-1);
    		System.out.println(s1); 								// 11111111,11111111,11111111,11111111
    		int i1 = Integer.valueOf("1111111100000000", 2);
    		System.out.println(i1); 								// 65280
    		int i2 = i1 >> 1;
    		System.out.println(Integer.toBinaryString(i2)); 		// 01111111,10000000
    		int i3 = i1 << 1;
    		System.out.println(Integer.toBinaryString(i3)); 		// 00000001,11111110,00000000
    		int i4 = i1 >>> 1;
    		System.out.println(Integer.toBinaryString(i4)); 		// 01111111,10000000
    		// 零位扩展和符号位扩展
    		System.out.println(Integer.toBinaryString(-1 >> 1)); 	// 11111111,11111111,11111111,11111111
    																// -1
    		System.out.println(Integer.toBinaryString(-1 >>> 1)); 	// 01111111,11111111,11111111,11111111
    																// 2147483647
    	}
    }
    

      Bitwise Operators(位运算符)

      &     |      ^(按位异或)   ~(按位取反)

      Logic Operators(逻辑运算符)

      &&  &  ||  |  !

      Conditional Operators(条件运算符)

      ?:

    public class Test {
    	public static void main(String[] args) {
    		boolean b = true;
    		int i = b ? 1 : 2;
    		System.out.println(i);	// 1
    	}
    }
    

      

      Other operators

      ++  --

    public class TestAction {
    
    	public static void main(String[] args) {
    		int i = 2;
    		System.out.println(i++);					// 2
    		System.out.println(i);						// 3
    		int a = i++ + i;						// 3+4=7
    		System.out.println(a);
    		int b = i++ + ++i;						// 3+5=10
    		i++;
    		System.out.println(b);
    		System.out.println(i);						// 7
    		for (int j = 0; j < 1000; j++) {
    			i = i++;
    		}
    		System.out.println(i);						// 7
    	}
    }
    

      

  • 相关阅读:
    第24天:Python 标准库概览2
    第23天:Python 标准库概览1
    第22天:Python NameSpace&Scope
    第21天: Web 开发 Jinja2 模板引擎
    第20天:Python 之装饰器
    第19天:Python 之迭代器
    第18天:Python 高阶函数
    第17天:Python 函数之参数
    第16天:Python 错误和异常
    第15天:Python set
  • 原文地址:https://www.cnblogs.com/diaoyan/p/5235655.html
Copyright © 2011-2022 走看看