百木园-与人分享,
就是让自己快乐。

java运算操作符示例大全

转自:

http://www.java265.com/JavaJingYan/202206/16557748673792.html

下文笔者讲述java运算操作符的示例大全

数值运算

public class Test {
  public static void main(String[] args) {
     int a = 22;
     int b = 12;
     int c = 90;
     int d = 90;
     System.out.println(\"a + b = \" + (a + b) );
     System.out.println(\"a - b = \" + (a - b) );
     System.out.println(\"a * b = \" + (a * b) );
     System.out.println(\"b / a = \" + (b / a) );
     System.out.println(\"b % a = \" + (b % a) );
     System.out.println(\"c % a = \" + (c % a) );
     System.out.println(\"a++   = \" +  (a++) );
     System.out.println(\"a--   = \" +  (a--) );
     System.out.println(\"d++   = \" +  (d++) );
     System.out.println(\"++d   = \" +  (++d) );
  }
}

关系运算

public class Test {
  public static void main(String[] args) {
     int a = 40;
     int b = 60;
     System.out.println(\"a == b = \" + (a == b) );
     System.out.println(\"a != b = \" + (a != b) );
     System.out.println(\"a > b = \" + (a > b) );
     System.out.println(\"a < b = \" + (a < b) );
     System.out.println(\"b >= a = \" + (b >= a) );
     System.out.println(\"b <= a = \" + (b <= a) );
  }
}

三元运算

public class Test {
    public static void main(String[] args) {
        int x, y, z; // 声明三个变量
        System.out.print(\"请输入一个数:\");
        Scanner input = new Scanner(System.in);
        x = input.nextInt(); // 由用户输入x的值
        // 判断x的值是否大于6,如果是y=x,否则y=-x
        y = x > 6 ? x : -x;
        // 判断y的值是否大于x,如果是z=y,否则z=5
        z = y > x ? y : 6;
        System.out.printf(\"x=%d \\n\", x);
        System.out.printf(\"y=%d \\n\", y);
        System.out.printf(\"z=%d \\n\", z);
    }
}

运算符优先级示例

public class TestClass{
    public static void main(String[] args){
        //运算符优先级测试
        //算术运算比关系运算优先级高
        System.out.println(3>1+4);//false
        System.out.println(3>2*5);//false
        //关系运算优先级大于逻辑运算
        System.out.println(3>1&true);//true
        System.out.println(3>1^true);//false
        //算术运算比位运算优先级高
        System.out.println(1+5<<2);//24
        System.out.println(1+5>>1);//3
        //位运算比关系运算优先级高
        System.out.println(5>1>>2);//true
        System.out.println(5>(1&1));//true
        System.out.println(5>-6>>>1);//false
        //取反优先级大于算术
        System.out.println(~5+1);//-5,不是-7
        System.out.println(~5*2);//-12

        //三元运算符
        //算术比三元高
        System.out.println(3>2?1:20+20);//1,不是21
        //三元比关系运算低
        Object r=3>2?1:9<3;//r=3>2?1:false
        System.out.println(r);//如果三元比关系高,返回false,否则返回1
        //三元比逻辑低 结果为true
        System.out.println(3>2?true:false&&false);//如果三元运算符优先,结果为false
        //三元比位(& | ^)低,结果是5
        System.out.println(3>2?5:8&1);//三元大于位,结果是1,三元小于位,结果是5
    }
} 

来源:https://www.cnblogs.com/java265/p/16395712.html
本站部分图文来源于网络,如有侵权请联系删除。

未经允许不得转载:百木园 » java运算操作符示例大全

相关推荐

  • 暂无文章