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
    	}
    }
    

      

  • 相关阅读:
    牛客小白月赛12 392B
    牛客392A 经典区间覆盖
    hihocoder contest95 1、3、4题目分析 2赛后补题
    hiho一下第234周《矩形计数》题目与解答
    Light oj 1306
    请访问我新的博客
    比特币“投资”记录-1
    如何清爽的使用网页版新浪微博
    Vuex/Vue 练手项目 在线汇率转换器
    重装macOS环境配置笔记
  • 原文地址:https://www.cnblogs.com/diaoyan/p/5235655.html
Copyright © 2011-2022 走看看