Java 数据类型区分与转换

Java 数据类型

八大基本数据类型区分

public class Demo02 {
    public static void main(String[] args) {
        //数据类型区分:
        //所有的字符本质还是数字
        //bit是Binary digit(二进制数位)的缩写,意为“位”或“比特”,是计算机运算的基础
        /*
        什么是byte?
        byte,即字节,由8位的二进制组成。在Java中,byte类型的数据是8位带符号的二进制数。
        在计算机中,8位带符号二进制数的取值范围是[-128, 127],所以在Java中,byte类型的
        取值范围也是[-128, 127]。
         */
        byte a = 6;
        System.out.println(a);
        //byte底层是8位二进制
        //该二进制数的取之范围是[-128,127]
        byte b = (byte) 180;
        System.out.println(b); //-76

        /*
        byte、short、int、long 、float、double区分:

        byte:[-128, 127]    8 bit 1字节
        short:[-3,2768, 3,2767]   16 bit 2字节
        int:[-21,4748,3648, 21,4748,3647]   32 bit 4字节
        long:[-2^63, 2^63-1]    64 bit 8字节  例:long a=10000L
        float:[10^-38, 10^38] 32 bit  4字节   例:float a=1.3f
        double:[10^-308, 10^308] 64 bit  8字节 例:double a=1.3

        char 是字符类型,无符号型的,占2字节(unicode码) [0-65535]
        char是一个16位二进制的unicode字符,java用char来表示一个字符

         */
    }
}

类型之间的转换

public class Demo04 {
    public static void main(String[] args) {
        int i = 128;
        byte b= (byte) i; //高到低强制转换导致内存溢出
        /*低---------------------------------------------->高
        byte,short,char ->  int -> long -> float -> double
        1、运算中,不同类型的数据先转换为同一类型,然后进行运算
        强制转换 (类型)变量名  高--低
        自动转换 低--高
         */

        System.out.println(i);
        System.out.println(b);

        /*注意点:
        1、不能对布尔值进行转换
        2、不能吧对象类型转换为不相干的类型
        3、在把高容量转换到低容量的时候,强制转换
        4、转换的时候可能存在内存溢出,或者精度问题
         */

        System.out.println("=============================");
        System.out.println((int)23.7); //23
        System.out.println((int)-45.89f); //45

        System.out.println("=============================");
        char c = 'a';
        int d = c+1;
        System.out.println(d);
        System.out.println((char)d);

    }
}

常见数据类型转换问题

public class Demo05 {
    public static void main(String[] args) {
        //操作比较大的时候,注意内存溢出问题
        //jdk新特性,数字之间可以用下划线分割
        int money = 10_0000_0000;
        int years = 20;
        int total = money*years; //-1474836480,计算的时候内存溢出了
        long total2 = money*years; //默认是int,转换前已经存在问题了?
        long total3 = money*((long)years); //先把一个数转换为long
        System.out.println(total3);
        
    }
}
posted @   夜久听山雨  阅读(58)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示