Java Data Type Conversion Methods
In Java, type conversion mainly involves the following methods:
- Implicit type conversion: Java will automatically perform type conversion when the destination type’s range is greater than the original type’s range, such as assigning an int type to a long type.
- When the target type has a smaller range than the original type, it is necessary to use a type casting to convert the data, such as converting a long to an int.
long num1 = 100;
int num2 = (int) num1;
- Automatic boxing and unboxing: The process of automatically converting between primitive data types and wrapper classes. Boxing is the conversion of a primitive data type into the corresponding wrapper class, while unboxing is the conversion of a wrapper class into the corresponding primitive data type.
int num1 = 100;
Integer num2 = num1; // 自动装箱
int num3 = num2; // 自动拆箱
- String conversion: Using the static method valueOf() in the String class allows for converting data of other types into a string, while using the static method parseXXX() in the wrapper class allows for converting a string into the corresponding primitive data type.
int num1 = 100;
String str1 = String.valueOf(num1); // int转换为String
String str2 = "200";
int num2 = Integer.parseInt(str2); // String转换为int