Java第六天

目录:

基本运算符、自增自检减运算符、初识Math类


1.基本运算符

Java语言支持如下运算符:

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

  • 复制运算符=

  • 关系运算符 >, <, >=, <=, ==, != instanceof

  • 逻辑运算符:&&, ||,!

  • 位运算符:&, |, ^, >>, <<, >>>

  • 条件运算符?:

  • 拓展赋值运算符: +=, -+,*=,/=

package code;
​
public class Main {
    public static void main(String[] args){
        //二院运算符
        //Ctrl+D:复制当前行到下一行
        int a = 10;
        int b = 22;
        int c = 25;
        int d = 25;
​
        System.out.println(a+b);
        System.out.println(a-b);
        System.out.println(a*b);
        System.out.println(a/(double)b);//强制把b的类型从int转为double
        System.out.println(b%a);//取余,也叫模运算
    }
}
/*输出结果为32
-12
220
0.45454545454545453
2*/
2.自增自检减运算符以及认识数学Math类
package operator;
public class Demo{
    //++ -- 表示自增自减,都属于一元运算符
    int a = 3;
    int b = a++;//执行完这行代码之后,先给b赋值,再自增
    //a++ a=a+1;
    int c=++a;//执行完这行代码之前,先自增,再给b赋值
    System.out.printIn(a);
    System.out.printIn(b);
    System.out.printIn(c);
    
    //幂运算2^3  2的三次方相当于2*2*2,计算的时候需要用到Math这个数学类 
    Math.pow(2,3);
​
}

//逻辑运算符:&&, ||,!

package operator;
public class Demo{
public static void main (String[] args){
boolean a = true;
boolean b =false;
    System.out.printIn("a && b:"+(a&&b));//与运算,两个变量都为真,结果才为true
    System.out.printIn("a || b:"+(a||b));//或运算,两个变量有一个为真,结果才为true
    System.out.printIn("!(a && b):"+!(a&&b));//非运算,如果是假,则为真。如果是真,则为假。
    
    
    //短路运算
    int c=5;
    boolean d =(c<4)&&(c++<4);
    System.out.printIn(d);
    System.out.printIn(c);
}
}
​
/*输出结果为 a && b:false
a || b:true
!(a && b):true
false
5   */

//位运算:&, |, ^, >>, <<, >>>

package operator;
public class Demo{
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
        位运算效率极高
    Systeam.out.printIn(2<<3);
    0000 0000   0
    0000 0001   1
    0000 0010   2
    0000 0011   3
    0000 0100   4
    0000 1000   8
    0001 0000   16 
     
    }
}
  • 条件运算符?:

    //三元运算符

    //x ? y : z

    //如果x==true,则结果为y,否则结果为z。

    int score = 80;//假设当前成绩为80分

    String type =score <60 ?"不及格" :"及格"; //必须掌握的点

    Systeam.out.printIn(type);

//输出为及格

  • 拓展赋值运算符: +=, -+,*=,/=

a+=b;//a=a+b

a-=b;//a=a-b

//字符串连接符 + ,String

int a=10;

int b=20;

Systeam.out.printIn(""+a+b);//字符串连接符在前面有效

Systeam.out.printIn(a+b+"");//字符串连接符在后面则无效

//输出为1020

//输出为30

  • 20
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值