Java learning diary day1

Java learning diary day1

type of data

Java is a strongly typed language, requiring the use of variables to strictly comply with regulations, and all variables must be defined before they can be used.

Java data types are divided into two categories: primitive types and reference types

public class Demo01 {
    
    
    public static void main(String[] args) {
    
    
        //八大基本数据类型
        //整数
        int num1 = 10;//最常用
        byte num2 = 20;
        short num3 = 30;
        long num4 = 40L;//long类型要在数字后面加个L(使用大写容易区分)
        //浮点数:小数
        float num5 = 50.5F;//float类型要在数字后面加个F(使用大写容易区分)
        double num6 = 3.1415926535;
        //字符
        char year = '牛';
        //字符串 String不是关键字是一个类
        String name = "李云龙";
        //布尔类型:值只能是true或者false
        //boolean a = true;

        System.out.println(num1);
        System.out.println(num2);
        System.out.println(num3);
        System.out.println(num4);
        System.out.println(num5);
        System.out.println(num6);
        System.out.println(year);
        System.out.println(name);
        //System.out.println(a);
    }
}

Type conversion

Since Java is a strongly typed language, type conversion is needed when doing some far-reaching calculations.

低------------------------------------->高
byte,short,char->int->long->float->double

In the operation, different types of data are first converted to the same type, and then the operation is performed.

public class Demo02 {
    
    
    public static void main(String[] args) {
    
    
        //类型转换
        //强制转换:(类型)变量名 从高到低
        int i = 128;
        byte b = (byte) i;//-128 内存溢出
        double d = i;//128.0 自动转换 从低到高
        System.out.println(i);
        System.out.println(b);
        System.out.println(d);
        System.out.println("====================");
        System.out.println((int)23.7);//23 精度损失
        System.out.println((int)-49.58F);//-49 精度损失

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

        System.out.println("====================");
        //操作较大的数的时候,注意溢出问题
        //JDK7新特性,数字之间可以用下划线分割
        int money = 10_0000_0000;//10亿
        int year = 20;
        int total = money * year;//-1474836480 计算的时候溢出了
        long total2 = money * year;//money和year默认是int,转换之前就已经存在溢出问题了
        long total3 = money * ((long)year);//先把一个数转换成long
        System.out.println(total);//-1474836480
        System.out.println(total2);//-1474836480
        System.out.println(total3);//20000000000
    }
}

Guess you like

Origin blog.csdn.net/Theend_7889/article/details/114109753