数据类型:
包装类与基本数据类型:
为了能将基本类型视为对象处理,并能连接相关方法,Java 为每个基本类型都提供了包装类。
基本类型 | 包装类 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
包装类:
Integer 类
构造方法:
- Integer(int value): 构造一个新分配的 Integer 对象,它表示指定的 int 值
- Integer(String s): 构造一个新分配的 Integer 对象,它表示 String 参数所指示的 int 值
Integer i1 = new Integer(100); //以 int 形变量作为参数创建 Integer 对象
Integer i2 = new Integer("200");//以 String 型变量作为参数创建 Integer 对象
Float 类:
构造方法:
- Float(double value):构造一个新分配的 Float 对象,它表示转换为 float 类型的参数
- Float(float value):构造一个新分配的 Float 对象,他表示基本的 float 参数。
- Float(String s):构造一个新分配的 Float 对象,它表示 String 参数所指示的 float 值。
Float float1 = new Float(3.14145);//以 doubule 类型的变量作为参数创建 Float
Float float2 = new Float(6.5);//以 Float 类型的变量作为参数创建 Float 对象
Float floats = new Float("3.1415");//以 String 类型的变量作为参数创建 Float
Chatacter 类
构造方法:
- Chatacter(char value): 构造一个新分配的 Character 对象,用以表现指定的char值
Boolean 类:
构造方法:
- Boolean(boolean boolValue): 通过boolean类型值来构建对象,其中boolValue必须时true或false (不区分大小写)
- Boolean(String boolString): 通过 String 类型值来构建对象, boolString 包含字符串ture(不区分大小写)
public static void main(String[] args){
Boolean b1 = new Boolean(ture);
Boolean b2 = new Boolean("ok");
Boolean b3 = new Boolean("ture");
System.out.println("b1 转换为 boolean 值时:"+ b1)
System.out.println("b2 转换为 boolean 值时:"+ b2)
System.out.println("b3 转换为 boolean 值时:"+ b3)
}
基础数据类型和包装类之间的转换
自动装箱:将基础数据类型的值赋值给包装类对象,需要调用包装类的 valueOf()进行装箱
自动拆箱:将包装类对象赋值给基础数据类型,需要调用该对象的xxxValue()进行拆箱
基础数据类型和字符串之间的转换
在实际的编程过程中,经常将字符串转换为int类型的数值,或者将int类型的数值转换为对应的字符串。
String str = "456";
int num = Integer.parseInt(str);//将字符串转换为 int 类型的数值 int i = 789
String s = Integer.toString(i);//将 int 类型的数值转换为字符串