02-07 Java language foundation (data type conversion)

Implicit conversion of data type conversion

Legal conversion between numeric types
In the figure, there are 6 solid arrows, indicating conversions without loss of information, and three dashed arrows, indicating conversions with possible loss of accuracy.

When connecting two values ​​with a binary operator, you need to convert the two operands to the same type, and then perform calculations:

  • If one of the two operands is of type double, the other operand will be converted to type double.
  • Otherwise, if one of the operands is of type float, the other operand will be converted to type float.
  • Otherwise, if one of the operands is of type long, the other operand will be converted to type long.
  • Otherwise, both operands will be converted to int type.

Float and long types are operated on and automatically converted to float type:

public class DataType01 {
    
    

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		//float和long类型进行运算,自动转换为float类型
		float a = 10;
		Long b = 11L;
		float c = a + b;
		System.out.println(c);
	}
}

Byte and int types are operated, and they are automatically converted to int type:

public class DataType02 {
    
    

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		byte a = 10;
		int b = 20;
		int c = a + b;
		System.out.println(c);
	}

}

Coercive type conversion of data type conversion

As we saw in the previous section, when necessary, the value of the int type will be automatically converted to the double type. But on the other hand, sometimes it is necessary to convert double to int. In Java, type conversion between such values ​​is allowed, and of course some information may be lost. This conversion of possible loss of information must be done through cast.

Cast double type variable to int type:

public class DataType03 {
    
    

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		double a = 37.5;
		System.out.println((int)a);
	}

}

Guess you like

Origin blog.csdn.net/qq_37054755/article/details/110790901