Conversion of Java basic data types

Java basics-data type conversion

Data type conversion in Java can be divided into two types: automatic conversion and forced conversion.

1. Automatic type conversion (implicit):

Features: The code does not require special processing and is automatically completed.
Rule: The data range is from large to small (Char→Byte→short→int→long—›float→double).
The following automatic type conversion has occurred:

public class Demo01 {
    
    

    public static void main(String[] args) {
    
    
    
		/**
         *  只要右边的变量类型的范围比左边的变量范围小都可以发生自动类型转换
         * */
         
        byte num1 = 10;
        System.out.println(num1);  //输出结果:10
        short num2 = num1;
        System.out.println(num2);  //输出结果:10
        int num3 = num2;
        System.out.println(num3);  //输出结果:10
        long num4 = num3;
        System.out.println(num4);  //输出结果:10
        float num5 = num4;
        System.out.println(num5);  //输出结果:10.0
        double num6 = num5;
        System.out.println(num6);  //输出结果:10.0
        
    }
}

2. Forced type conversion (implicit):

Features: The code needs special processing and is not automatically completed.
Format: [Type with small data range] [Variable name] = (Type with small data range) [Type with large data range you need to convert].
For example, the following example:

	public class Demo01 {
    
    

    public static void main(String[] args) {
    
    

        /**
         * 左边是int类型,需要将long类型赋值给int类型
         * long类型的数据范围比int类型大
         * 不能发生自动类型转换,需要特殊处理
         * 格式:[数据范围小的类型] [变量名]  = (数据范围小的类型)[你需要转换的数据范围大的类型]
         */


        //int num1 = 100L;  //如果不进行特殊处理,这段代码直接编译器爆红,需要强转,如下:
        int num1 = (int)100L;  //对long类型进行了强制转换int类型,括号里面的就是你需要转换的类型
		System.out.println(num1);  //输出结果:100
		
		//如果你要把浮点型的数据强制转换,可能会发生精度丢失,如下:
		int num2 =  (int)36.18;
		System.out.println(num1);   //结果为:36
		//这里需要注意的是精度丢失不是四舍五入,而是直接丢弃小数点后面的数
		long num3 = (long)39.9F;
		System.out.println(num3);  //结果为:39,而不是40
		short num4 = (short)39.9;
		System.out.println(num4);  //结果还是39
		// ......
    }
}

After reading the data type conversion, a careful person may find: In the above implicit type conversion example, the number 10 should not be of type int. Why can it be directly given to byte and short, according to the rules of implicit type conversion : The data range needs to be from large to small in order to be implicitly converted. Why is int larger than byte and short, but does not require forced type conversion?

public class Demo01 {
    
    

    public static void main(String[] args) {
    
    
		
		//直接写数字默认是int,为什么给byte、short不需要强转?
        byte num1 = 127;  
        short num2 = 32767;

		/**
		*这是因为:Java中规定所有整数默认是int型。
		*但是只要在byte,short它们的取值范围内赋值都是可以的
		*比如byte=127 就是可以的给byte=128  就不行了 因为就超出byte 127 的最大范围了。
		*/
		byte num3 = 128;  //超过byte范围编译器直接报错
		short num4 = 32768; //超过short范围编译器直接报错
    }
}

Guess you like

Origin blog.csdn.net/weixin_47316336/article/details/108864143