Java中基本类型、包装类和String类型及其之间的转换
Java中提供了将基本数据类型转换为对象,以及将对象转换为基本数据类型的机制。
基本类型不能为null,但包装类可以为null,且包装类可用于实现多态性。
java.lang 包的八个类在Java中被称为包装类。
基本数据类型 | 包装类 |
---|---|
boolean | Boolean |
char | Character |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
1.基本类型和包装类转换为String类型
1.1连接运算
int num2 = 100;
String str2 = num2 + "";
System.out.println(str2 + 1);//1001
1.2.调用String的valueof(Xxx xxx)
float f2 = 12.5f;
String str22 = String.valueOf(f2);
Double d2 = new Double(12.5);
String str23 = String.valueOf(d2);
System.out.println(str22+1);//12.51
System.out.println(str23+1);//12.51
2.将String数据类型转换为基本数据类型和包装类,使用parseXxx
String str3 = "123";
System.out.println(str3 + 1);//1231
int num3 = Integer.parseInt(str3);
System.out.println(num3 + 1);//124
String str31 = "true";
boolean b3 = Boolean.parseBoolean(str31);
if(b3) {
System.out.println(b3);//true
}
代码示例:
package Day4;
import org.junit.Test;
/*
包装类的使用
*/
public class WrapperTest {
//基本数据类型:包装类
@Test
public void test1(){
int num1 = 10;
Integer in1 = new Integer(num1);
System.out.println(in1);//10,warning:unnecessary toStaring() call
Integer in2 = new Integer("123");
System.out.println(in2);//123
// Integer in3 = new Integer("123abc");
// System.out.println(in3.toString());//wrong
Float f1 = new Float(12.3F);
Float f2 = new Float("12.3");
System.out.println(f1);//12.3
System.out.println(f2);//12.3
}
//基本类型、包装类转换为String类型
@Test
public void test2(){
int num2 = 10;
//1.连接运算
String str2 = num2 + "";
//2.调用String的valueof(Xxx xxx)
float f2 = 12.5f;
String str22 = String.valueOf(f2);
Double d2 = new Double(12.5);
String str23 = String.valueOf(d2);
System.out.println(str22);
System.out.println(str23);
}
//String数据类型转换为基本数据类型和包装类,使用parseXxx
@Test
public void test3(){
String str3 = "123";
System.out.println(str3 + 1);//1231
int num3 = Integer.parseInt(str3);
System.out.println(num3 + 1);//124
String str31 = "true";
boolean b3 = Boolean.parseBoolean(str31);
if(b3) {
System.out.println(b3);//true
}
System.out.println("********************");
}
@Test
public void test4(){
Object o1 = true ? new Integer(1) : new Double(2.0);//三元运算符,两边同类型,统一到Double
System.out.println(o1);
}
@Test
public void test5(){
Object o2;
if(true){
o2 = new Integer(1);
}else {
o2 = new Double(2.0);
}
System.out.println(o2);
}
@Test
public void test6(){
Integer i = new Integer(1);
Integer j = new Integer(1);
System.out.println(i == j);//false 比较地址值
//自动装箱
//Integer 内部定义了IntegerCache结构,保存了-128-127范围的整数
Integer m = 1;
Integer n = 1;
System.out.println(m == n);//true 源码里存储常用数组,指向同一个1
Integer x = 128;
Integer y = 128;
System.out.println(x == y);//false 数组范围[-128-127],超出范围
}
}