java基础02

shiweirui / 2023-08-14 / 原文

数据类型扩展

  1. 进制,二进制以0b开头,八进制以0开头,十六进制以0x(x必须为小写)开头,如:
public class hello {
    public static void main(String[] args) {
        int i = 0b10;//二进制
        int i2 = 10;//十进制
        int i3 = 010;//八进制
        int i4 = 0x10;//十六进制

        System.out.println(i);
        System.out.println(i2);
        System.out.println(i3);
        System.out.println(i4);
    }
}

输出结果:

2
10
8
16

Process finished with exit code 0

  1. 浮点数扩展,如银行业务怎么表示?钱
  • floot

  • double

  • 浮点数表示词长是有限的离散的,存在舍入误差,只能表示大约数,接近但是不等于

    如:

public class hello {
    public static void main(String[] args) {
        float f = 0.1f;
        double d = 0.1;
        System.out.println(f==d);
    }
}

输出结果:

false

Process finished with exit code 0

又比如:

public class hello {
    public static void main(String[] args) {
        float f = 1212121212112121211211f;
        float d = f+1;
        System.out.println(f==d);
    }
}

输出结果:

true

Process finished with exit code 0
  • 最好完全避免使用浮点数进行比较
  • 所以银行业务怎么表示?既然不能用基础数据类型,那就用类:BigDecimal,是一个数学工具类
  1. 字符扩展:输出语句加上int可以强制转换,转换成数字

如:

public class hello {
    public static void main(String[] args) {
        char c1 = 'a';
        char c2 = '啊';


        System.out.println(c1);
        System.out.println((int)c1);
        System.out.println(c2);
        System.out.println((int)c2);
    }
}

输出结果:

a
97
啊
21834

Process finished with exit code 0
  • 所有字符的本质还是数字
  • 这里边涉及到编码,Unicode,占两个字节,可以从0写到65536,也就是2的16次方,表内有数字对应不同字符如97=a,65=A

表示方式为U0000到UFFFFF,如:

public class hello {
    public static void main(String[] args) {
        char c1 = '\u0061';

        System.out.println(c1);

    }
}

输出结果:

a

Process finished with exit code 0
  • 转义字符就是有特殊的意思,如:\t代表制表,\n代表换行等等
public class hello {
    public static void main(String[] args) {

        System.out.println("hello\tworld");
        System.out.println("hello\nworld");
    }
}

输出结果:

hello	world
hello
world

Process finished with exit code 0
  1. 布尔值扩展if(==)和if()效果等同,如:
public class hello {
    public static void main(String[] args) {

        boolean flag = true;
        if (flag==true){
            System.out.println(1);
        }
        if (flag){
            System.out.println(1);
        }
    }
}

输出结果:

1
1

Process finished with exit code 0