Java教程

基本运算符

本文主要是介绍基本运算符,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

基本运算符

算术运算符:+,-,*,/,%,++,--

赋值运算符:=

关系运算符:>,<,>=,<=,==,!=

逻辑运算符:&&(与),||(或),!(非)

位运算符:&,|,^,~,>>,<<,>>>(了解)

条件运算符:?:

扩展运算符:+=,-=,*=,/=

1、自增(++)自减(--)运算符是一种特殊的算术运算符,在算术运算符中需要两个操作数来进行运算,而自增自减运算符是一个操作数。

public class selfAddMinus{   
    public static void main(String[] args){ 
        public class demo4 {

    public static void main(String[] args) {
        //自增 自减 一元运算符 按顺序走
        int a = 3;
        int b = a++;//执行完代码后,先给b赋值,在自增
        //a = a+1
        System.out.println(a);//4
        //a = a+1
        int c = ++a;//执行完代码前,先自增,在给c赋值
        System.out.println(a);//5
        System.out.println(b);//3
        System.out.println(c);//5
        
        //下面同理
        System.out.println("==============================");

        int a1 = 3;
        int b1 = a1--;
        //a1 = a1-1 //2
        System.out.println(a1);//2
        //a1 = a1-1 
        int c1 = --a1;//1
        System.out.println(a1);//1
        System.out.println(b1);//3
        System.out.println(c1);//1

    }
}

2.逻辑运算

public class demo3 {
    public static void main(String[] args) {
        //与 (and) 或 (or) 非 (取反)
        boolean a = true;
        boolean b = false;
        System.out.println(a && b);//false  //与运算:两个为真,才是true
        System.out.println(a || b);//true  //或运算:一个为真,就是true
        System.out.println(!a);//false   //取反

        System.out.println("=============================================");

        //短路运算
        int c = 5;
        boolean d = (c < 44) && (c++ < 4);
        boolean d1 = (c < 44) || (c++ < 4);
        System.out.println(d);//false
        System.out.println(d1);//true


    }
}

3.位运算

public class demo5 {

    public static void main(String[] args) {

        /*
        A = 0011 1100
        B = 0000 1101
        ---------------------
        A&B 0000 1100
        A|B 0011 1101
        A^B 0011 0001
        ~B  1111 0010
        * */
        //2*8 = 16  2*2*2*2
        //效率极高
        // << *2
        // >> /2

        System.out.println(2 << 3);// 16
    }
}

  1. 条件运算符,和扩展运算

    public class demo6 {
        public static void main(String[] args) {
            //条件运算 三元运算
            // x ? y : z
            //如果x==true,结果位y,否则为z
            int tets = 59;
            String type = tets >= 60 ? "及格" : "不及格";
            System.out.println(type);
    
            System.out.println("============================= ");
    
            //扩展运算
            int a = 10;
            int b = 20;
    
            a += b; //a= a+b
            a -= b; //a = a-b
    
            System.out.println(a); //10
    
            //字符串连接符 + ,String
            System.out.println("" + a + b);//1024 ""在前面会将+号后面连接不计算
            System.out.println(a + b + "");//30  ""在后面正常计算
    
    
        }
    }
    
这篇关于基本运算符的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!