逻辑运算符,位运算符,三元运算符,扩展运算符

逻辑运算符,位运算符,三元运算符,扩展运算符

逻辑运算符

package operator;

public class Demo05 {
    public static void main(String[] args) {
        //逻辑运算符 与(and)&&, 或(or)||, 非(取反)[!()]
        boolean a = true;
        boolean b = false;
        System.out.println("a && b:"+(a&&b));//逻辑与运算,只有两个变量都为真,结果才为true
        System.out.println("a || b:"+(a||b));//逻辑或运算,两个变量其中一个变量为真,结果为true
        System.out.println("!(a && b):"+!(a&&b));//逻辑非运算,结果为真则结果为假,反之为真

        //短路运算
        int c = 6;
        boolean d = (c<3)&&(c++<10);
        System.out.println(d);//输出为false
        System.out.println(c);/*其中按照逻辑与运算应该会输出false之后c为7,
                                可是因为前一个条件(c<3)为false,
                                所以不会继续对下一个条件(c++<10)进行判断
                              */
        
    }
}

位运算

package operator;

public class Demo06 {
    public static void main(String[] args) {
        //位运算
        /*/
        A = 1000 0110
        B = 0011 1011
        ------------------------------
        A&B =0000 0010 与
        A|B =1011 1111 或
        A^B =1111 1101 异或
        ~B = 1100 0100 取反
        ------------------------------
        2*8怎么运算最快?
        <<(左移)相当于数字*2
        >>(右移)相当于数字/2
        效率极高!!!!!
        0000 0000        0
        0000 0001        1
        0000 0010        2
        0000 0100        4
        0000 1000        8
        0001 0000        16
         */
        System.out.println(2<<3);
    }
}

三元运算符

package operator;

import org.w3c.dom.ls.LSInput;

//三元运算符
public class Demo08 {
    public static void main(String[] args) {
        //x ? y : z
        //如果x==true,则结果为y,否则结果为z
        int score = 50;
        String type = score < 60?"不及格":"及格";
        System.out.println("考试成绩"+type);
    }
}

扩展运算符

package operator;

public class Demo07 {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        a+=b;//相当于a=a+b,a=30
        //a-=b;相当于a=a-b,a=-10.若与上面a+=b结合则a=30-20=10
        System.out.println(a);

        //字符串连接符 + ,String
        System.out.println(a+b);
        System.out.println(""+a+b);//当string类型在前面时则会将整段都转换成string类型
        System.out.println(a+b+"");//当前面不是string类型时则会先运算输出对应类型的结果再加上string字符串
    }
}

posted @ 2026-02-13 18:50  星之奔流  阅读(6)  评论(0)    收藏  举报