Table of contents
1. String (String) to integer (int):
2. Integer (int) to string (String):
3. String (String) to floating point number (float):
4. Floating point number (float) to string (String):
5. String (String) to Boolean (boolean):
6. Boolean (boolean) to string (String):
7. String (String) to character array (char[]):
8. Character array (char[]) to character string (String):
When it comes to converting between data types, Android provides many built-in methods and operators to simplify the process. Below are some common data type conversion examples, including comments to help you understand.
1. String (String) to integer (int):
String str = "123";
int num = Integer.parseInt(str); // 将字符串转换为整数
2. Integer (int) to string (String):
int num = 123;
String str = Integer.toString(num); // 将整数转换为字符串
3. String (String) to floating point number (float):
String str = "3.14";
float num = Float.parseFloat(str); // 将字符串转换为浮点数
4. Floating point number (float) to string (String):
float num = 3.14f;
String str = Float.toString(num); // 将浮点数转换为字符串
5. String (String) to Boolean (boolean):
String str = "true";
boolean bool = Boolean.parseBoolean(str); // 将字符串转换为布尔值
6. Boolean (boolean) to string (String):
boolean bool = true;
String str = Boolean.toString(bool); // 将布尔值转换为字符串
7. String (String) to character array (char[]):
String str = "hello";
char[] arr = str.toCharArray(); // 将字符串转换为字符数组
8. Character array (char[]) to character string (String):
char[] arr = {'h', 'e', 'l', 'l', 'o'};
String str = new String(arr); // 将字符数组转换为字符串
9. Convert boolean to integer
In Java, Boolean values can be implicitly converted to integer types. When boolean true
, it is converted to integer 1
; when boolean false
, it is converted to integer 0
. Here is an example:
boolean bool = true;
int num = bool ? 1 : 0; // 将布尔值转换为整数
In the above example, ?:
the boolean value is bool
converted to an integer using the conditional operator. If bool
yes true
, the integer 1
is assigned to num
; if bool
yes false
, the integer 0
is assigned to num
.
This implicit conversion can be used in many situations, such as using boolean values for mathematical operations, assignment operations, etc. If you need to convert a Boolean value to a String type, you can use the Boolean toString()
method.