Java数据类型及数据类型转换

数据类型

1、基本类型(Primitive Type)

(1)数值类型:

整数类型:

byte:占1个字节 范围:-128-127
short:占2个字节 范围:-32768-32767
int:占4个字节 范围:-2147483648-2147483647
long:占8个字节 范围:-9223372036854775808-9223372036854775807

浮点类型:

float:占4个字节
double:占8个字节

字符类型:

char:占2个字节

(2)boolean类型:

占1位,其值只有true和false两个

public class Main {
    public static void main(String[] args) {
        //八大基本数据类型

        //整型
        byte num1 = 10;    //最常用
        short num2 = 20;
        int num3 = 30;
        long num4 = 40L;   //Long类型要在数字后面加L来和其他的进行区分

        //浮点型
        float num5 = 50.5F;   //Float类型要在后面加F来和Double类型进行区分
        double num6 = 66.666666666666666;

        //字符型
        char name1 = 'A';
        char name2 = '我';
        //String name3 = "你我他";  //字符串,String不是关键字,是类

        //布尔型: 0 1
        boolean flag = true;
        //boolean flag = false;

    }
}

2、引用类型(Reference Type)

类、接口、数组


数据类型转换

低------------------------------------------>高
   byte,short,char->int->long->float->double
    
强制转换:    (类型)变量名     高-->低
自动转换:      低-->高


public class Main {
    public static void main(String[] args) {
        int i = 128;
        byte b = (byte)i; //内存溢出
        double d = i;

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

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

        System.out.println("===============");
        System.out.println((int)3.1415926);   //3
        System.out.println((int)-8.8888f);    //-8

        System.out.println("===============");
        char n = 'a';
        int m = n + 1;

        System.out.println(m);          //98
        System.out.println((char) m);   //b


        //操作比较大的数的时候,注意溢出问题
        //JDK7新特性:数字之间可以用下划线分割
        int money = 10_0000_0000;
        int years = 20;
        int total1 = money * years;  //-1474836480,计算的时候溢出了
        long total2 = money * years; //默认是int,转换之前已经存在问题

        long total3 = money * ((long)years);
        System.out.println(total1);
        System.out.println(total2);
        System.out.println(total3);
    }
}
posted @ 2022-12-31 20:41  赤心木9  阅读(91)  评论(0)    收藏  举报