Java学习——数据类型知识拓展及其转换

发布时间 2023-06-28 11:10:14作者: 菲菲公主的博客

数据类型知识扩展和转换

什么是字节?

  • 位(bit) 计算机 内部数据 储存的最小单位
  • 字节(byte)计算机 数据处理的基本单位 习惯用B表示
  • 1B(byte)=8b(bit)
  • 1bit 表示1位
  • 1B=8b 1024B=1KB 1024KB=1MB 1024MB=1G
	//整数
    int num1 = 1000;
    byte num2 = 20;
    short num3 = 30;
    long num4 = 30L;
	//小数:浮点数
        float num5 = 50.1F;
        double num6 = 3.1415926;
	//字符类型
        char name = 'A';
	//布尔值
        boolean flag = true;
        boolean flag2 = false;

//整数拓展 进制 二进制0b 十进制 八进制0 十六进制0x
        int i = 10;
        int i2 = 010;//八进制0
        int i3 = 0x10;//十六进制0x 0~9 A~F 16
        System.out.println(i);
       System.out.println(i2);
        System.out.println(i3);
 
//浮点数拓展
        float f = 0.1f;//0.1
        double d = 1.0 / 10;//0.1
        System.out.println(f == d);//false
		//眼看两个数的结果应该是一样的,但是程序运行出来却不是
		//最好不用float与double比较
		//最好完全 避免使用 浮点数进行比较
        float d1 = 2222222222222f;
        float d2 = d1 + 1;
        System.out.println(d1 == d2);//true
//字符拓展
        char c1 = 'a';
        char c2 = '中';
        System.out.println(c1);
        System.out.println((int) c1);//强制执行
        System.out.println(c2);
        System.out.println((int) c2);//强制执行
        //所有的字符本质还是数字
        //编码 Unicode 表:(97 =a 65=A)2字节 0-65536
        //U0000 UFFFF
        char c3 = '\u0061';
        System.out.println(c3);//a

 //转义字符
        // \t 制表符
        // \n换行
        // ...
        System.out.println("Hello\nworld");

        String sa = new String("hello world");
        String sb = new String("hello world");
        System.out.println(sa == sb);//false
        String sc = "hello world";
        String sd = "hello world";
        System.out.println(sc == sd);//true

//对象 从内存分析
//布尔值扩展
        boolean flag1 = true;
        if (flag1 == true) {
        }//新手
        if (flag) {
        }//老手
        //代码要精简已读

数据类型转换

优先级

byte short char——》int——》long——》float——》double

需要注意的问题

  1. 不能对布尔值进行数据类型转换
  2. 不能把对象类型转换为不相干的类型
  3. 再把高容量转换到低容量的时候,强制转换
  4. 转换的时候可能存在内存溢出 或者精度问题。
 	   int i = 128;
        byte b = (byte) i;//内存溢出
        double d = i;
//强制类型转换(类型)变量名 高----低
//自动转换    (类型)低---高
        System.out.println(i);
        System.out.println(b);
        System.out.println(d);

        System.out.println((int) 23.7);//23
        System.out.println((int) -45.87f);//-45

        //操作比较大的时候 注意溢出问题
        //jdk7新特性 数字之间可以用下划线分割
        int money = 10_0000_0000;
        int years = 20;
        int total = money * years;//-1474836480 计算的时候溢出了
        long total2 = money * years;
	//和上面结果一样 默认是int 转换之前已经存在问题了
        System.out.println(total);
        System.out.println(total2);
        long total3 = money * ((long) years);
	//先把一个数转换为long,再进行计算
        System.out.println(total3);