When a Java program performs assignment or operation, it automatically converts small precision into large precision.
char —> int —> long —> float —> double
byte —> short —> int —> long —> float —> double
When there are multiple data mixed operations, the system will first automatically convert all data into the data type with the largest capacity, and then perform calculations.
When assigning a data type with a high precision to a data type with a small precision, an error will be reported. Note that when assigning a numerical value, first determine whether it is within the range of the small-precision data type. If so, it is OK. If it is a variable assignment, it is not OK.
Byte, short and char cannot be automatically converted to each other.
byte, short and char can be calculated and converted into int type during calculation.
Boolean type does not participate in conversion.
Auto-promotion principle: The type of the expression result is automatically converted to the largest type among the operands.
The reverse process of automatic type conversion, converting data types with large capacity into data types with small capacity data type. A coercion character must be added when using it, but this may cause precision reduction or overflow.
Forced type conversion is only effective for the most recent operand, and parentheses are often used to increase the priority.
The char type can save the constant value of int, but it cannot save the variable value of int and needs to be forced.
public class ForceTest{ public static void main(String []args){ int x = (int)(10*3.5+6*1.5);//正确 int y = (int)10*3.5+6*1.5;//报错 } }
Just "" the value of this type.
int n1 = 100; String str1 = n1 + "";
Just call the parseXX function through the wrapper class of the basic data type, but make sure that the String type can be converted into valid data, for example, you can convert " 123" conversion, but "hello" cannot be converted into an integer. If the format is incorrect, an exception will be thrown and the program will be terminated.
String Str1 = "345"; Integer.parseInt("123"); Double.parseDouble("123.5"); Float.parseFloat("123.3"); Short.parseShort("123"); Boolean.parseBoolean("true"); Long.parseLong("123456"); Byte.parseByte("12"); //将字符串转换成字符型需要调用charAt(int a)函数 Str1.charAt(a); //表示字符串中第a+1个字符 Str1.charAt(0)='3';
The above is the detailed content of How to convert between Java basic data types. For more information, please follow other related articles on the PHP Chinese website!