Java基础----算数运算符,赋值运算符,比较运算符,逻辑运算符,三元运算符

运算符的分类:
1算数运算符
2赋值运算符
3比较运算符
4逻辑运算符
5三元运算符

1.算数运算符

在这里插入图片描述
练习

public static void main(String[] args) {
   int i = 6666;  
   System.out.println(i/1000*1000);//计算结果是6666
}

前++与后++的区别:
1.变量在独立运算时, 前 ++ 和 后 ++ 没有区别 。
2.变量 前 ++ :例如 ++i 。
3.变量 后 ++ :例如 i++

public static void main(String[] args) {
    int a = 1;
    int b = ++a;
    System.out.println(a);//计算结果是2
    System.out.println(b);//计算结果是2
}
public static void main(String[] args) {
    int a = 1;
    int b = a++;
    System.out.println(a);//计算结果是2
    System.out.println(b);//计算结果是1
}

+符号在字符串中的操作: +符号在遇到字符串的时候,表示连接、拼接的含义。

public static void main(String[] args){
  System.out.println("10+10="+10+10);//输出10+10=1010  
}

2.赋值运算符

在这里插入图片描述

public static void main(String[] args){
    int i = 10;
    i+=5;//计算方式 i=i+5 变量i先加5,再赋值变量i
    System.out.println(i); //输出结果是15
}

+= 符号的扩展

public static void main(String[] args){
  short s = 1;
  s+=1;
  System.out.println(s);
}

s=s+1 进行两次运算 , += 是一个运算符,只运算一次,并带有强制转换的特点,也就是说 s += 1 就是 s = (short)(s + 1) ,因此程序没有问题编译通过,运行结果是2.

3.比较运算符

在这里插入图片描述

public static void main(String[] args) {
    System.out.println(1==1);//true
    System.out.println(1<2);//true
    System.out.println(3<=4);//true
    System.out.println(3!=4);//true
}

4.逻辑运算符

在这里插入图片描述

public static void main(String[] args)  {
    System.out.println(true && true);//true
    System.out.println(true && false);//false
    //因为左边的false就能确定这个运算符的值为false,所有右边不进行计算
    System.out.println(false && true);//false,右边不计算
    System.out.println(false || false);//falase
    System.out.println(false || true);//true
    System.out.println(true || false);//true,右边不计算
    System.out.println(!false);//true
}

5.三元运算符

格式:

	数据类型 变量名 = 布尔类型表达式?结果1:结果2

布尔类型表达式结果是 true,三元运算符整体结果为"结果1",赋值给变量。
布尔类型表达式结果是 false,三元运算符整体结果为"结果2",赋值给变量。

扫描二维码关注公众号,回复: 11582729 查看本文章
public static void main(String[] args) {
    int i = (10==20 ? 100 : 200);
    System.out.println(i);//200
    int j = (30<=40 ? 300 : 400);
    System.out.println(j);//300
}

猜你喜欢

转载自blog.csdn.net/Mrxuanshen/article/details/107935184