- 针对八种基本数据类型定义相应的应用类型–包装类(封装类)
基本数据类型 | 包装类 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
boolean | Boolean |
char | Character |
基本数据类型,包装类和String类之间的转化:
基本数据类型–》包装类
class order{
boolean ismale;
Boolean isfemale;
}
public class JUnitTest {
//基本数据类型-》包装类
@Test
public void test1() {
int num1 = 10;
//System.out.println(num1.toString());//基本数据类型没有方法
Integer in1 = new Integer(num1);
System.out.println(in1.toString());//10
Integer in2 = new Integer("123");
System.out.println(in2.toString());
//报异常
// Integer in3 = new Integer("123aabc");
// System.out.println(in3.toString());
Float f1 = new Float("12.3");
Float f2 = new Float(12.3f);
System.out.println(f1);
System.out.println(f2);
Boolean b1 = new Boolean(true);
Boolean b2 = new Boolean("true");
Boolean b3 = new Boolean("abc123");//不报错,只要不等于true(不区分大小写)就返回false
System.out.println(b3);
order o = new order();
System.out.println(o.ismale);//false
System.out.println(o.isfemale);//null
}
}
包装类–》基本数据类型
调用包装类的xxxValue()
//包装类--》基本数据类型,调用包装类的xxxValue()
@Test
public void test2(){
Integer in1 = new Integer(12);
int i1 = in1.intValue();
System.out.println(i1 + 1);
Float f1 = new Float(12.3f);
float f2 = f1.floatValue();
System.out.println(f2 + 1);
}
自动装箱与自动拆箱
可以把包装类当做基本数据类型用
@Test
public void test3(){
//自动装箱:基本数据类型--》包装类
int num2 = 10;
Integer in1 = num2;
boolean b1 = true;
Boolean b2 = b1;
System.out.println(num2 + " " + in1 + " " + b1 + " " + b2);
//自动拆箱:包装类--》基本数据类型
int num3 = in1;
System.out.println(num3);
}
基本数据类型,包装类–》String类型
@Test
public void test4(){
//方式一:连接运算
int num = 10;
String s1 = num + "**";
System.out.println(s1);
//方式二:调用String重载的valueOf()方法
float f1 = 12.3f;
String s2 = String.valueOf(f1);//"12.3"
System.out.println(s2);
Double d1 = new Double(14.5);
String s3 = String.valueOf(d1);
System.out.println(s3);
}
String类型–》基本数据类型,包装类
调用包装类的parsexxx(String s)
@Test
public void test5(){
//String str1 = "123ddf";//报错
String str1 = "123";
int num2 = Integer.parseInt(str1);
System.out.println(num2 + 1);
String str2 = "true1";
boolean b1 = Boolean.parseBoolean(str2);
System.out.println(b1);
}