Java-type conversion of basic types

The 7 basic data types provided by Java can be converted to each other, and there are 2 conversion methods: automatic type conversion and forced type conversion.

1 Automatic type conversion

If the system supports the direct assignment of a value of a basic type to a variable of another basic type, this method is called automatic type conversion.

Basic data type conversion

When a value or variable with a small table number range is directly assigned to another variable with a large table number range, the system can perform automatic type conversion, otherwise it must perform a forced type conversion.
Insert picture description here
The left side of the above picture can be automatically converted to the right side.
Note that char and byte, char and short cannot be automatically converted

public class AutoConversion{
    
    
	public static void main(String[] args){
    
    
		//int转换成float
		int a=1;
		float f=a;	//输出1.0
	}
}

Basic data type to String

The string type is not a basic type, but a reference type.
When the value of any basic type is concatenated with a string, the value of the basic type will automatically be converted to a string type.

public class ToString{
    
    
	public static void main(String[] args){
    
    
		String s1=3.5f+"";	//s1="3.5"
		String s2=1+2+"";	//s2="3"
		String s3="0"+1+2;	//s3="012"
	}
}

2 forced type conversion

If a number with a large range is converted to a number with a small range, it may cause overflow and cause data loss. This conversion page is called "Narrow Conversion".

public class NarrowConversion{
    
    
	publci static void main(String[] args){
    
    
		int a=233;
		byte b=(byte)a;	//b=-23
	}
}

Insert picture description here
Strings cannot be directly converted to basic types, but they can be passed through the wrapper class

String s="12";
int a=Integer.parseInt(s);

boolean-Boolean
byte-Byte
short-Short
int-Integer
long-Long
char-Character
float-Float
double-Double
8 package classes provide a parseXxx(String str)

Regarding the float type:
float f=5.6 This will cause an error, because 5.6 defaults to the double type,
so it should be: float f=(float)f;

3 Automatic promotion of expression type

When an arithmetic expression contains multiple basic types of values, the data type of the entire arithmetic expression will be automatically promoted. Java defines the following promotion rules:

  • All byte type, short type, char type will be promoted to int type
  • The data type of the entire arithmetic expression is automatically promoted to the same type as the highest level operand in the expression.
    Insert picture description here
    Insert picture description here

Guess you like

Origin blog.csdn.net/qq_42713936/article/details/105756343