(八)java运算符

  • 算数运算符
    • + - * / % ++ --
class  Ysf
{
    public static void main(String[] args)
    {
        System.out.println(5/2);//2默认为int类型
 
        System.out.println(5/2.0);//2.5修改为double类型
 
        System.out.println(-5 % 2);//-1
        System.out.println(5 % 2);//1取余结果的正负由被除数决定
 
        //如何得到整数的个位,十位,百位。
        int num = 345;
        System.out.println(num % 10 + num/10%10 + num/100);
 
        
        int m = 5,n;
        m++;//++在后先将m的值赋给左边变量,自身在加1,++在后,m自身先+1,然后再将结果赋给左边的变量
        //System.out.println("m=" + m);//6
        n = m++;
        System.out.println("m=" + m+ "n="+ n);//m:6,n:5
 
    int  a = 5,b = 3,s;
        s = a++ + ++a + --b - b--; //a++以后a的值变为6,但是这个位置上取的值还是5, ++a后,a的值为7,该位置取得值也为7
        //s = 5 + 7 + 2 - 2
        System.out.println("s:" + s);// 5 a:6, 7 a:7, 2 b:2, 2 b:1
    }
}

  

  • 赋值运算符
    •  = ,+=, -=, *=, /=
 
       int c = 5,d = 3,e;
        e = c + d;//8
        c += d;// c = c + d 8
        c *= d;// c = c * d 15
        c /= d;// c = c / d 小数
 
 
        byte j = 5,f;
        f = j +6;
        System.out.println("f" + f);//编译不通过,j为byte类型。而6默认为int型,int转换为byte可能损失精度
        byte j = 5,f;
        f +=6;
        System.out.prinltn("f" + f);//结果为11,编译通过,采用复合运算符,内部做了自动转换。

  

  • 关系运算符
    • >,>=,<,<=<,==,!=
System.out.prinltn(5>3);//true
System.out.prinlnt(5<3);//false
System.out.println(5==3);//false

  

  • 逻辑运算符
    • &&与, ||或 , !非(取反)
int yu = 90,shu = 70;
System.out.println(yu>=90 && shu>=90);//false条件都满足时才为true
true &&  true ;//true
true && false;//false
false && false;//false
false && true;//false
 
/*
    &&:左边的表达式为false 最终结果为假剩下的就不会去运算,运行效果会快一些
        &:左边的为false,还会继续运算右侧表达式,运行效率会慢一些
        ||;如果左边为true,剩下的就不会去计算,运行效率快一些
        ||:如果左边为true,剩下的还回去计算,运行效率会慢一些。
注:因此在开发 时,一般多使用&&,||来进行逻辑运算
*/
 
System.out.println(yu>=90 || shu>=90);//true只要满足一个就为true
true || true;//true
true || false;//true
false || true;//true
false || false;//false
 
System.out.print(!(5<3));//true

  

  • 条件运算符
int m,n = 5;
m= n>5?66:55;//m = 55

  

原文地址:https://www.cnblogs.com/bgwhite/p/9299078.html