(基本数据类型+包装类) 和 String 相互转化
(基本数据类型+包装类) 和 String 相互转化
1. 基本数据类型,包装类 -> String
1.1. 之前的做法: 连接运算
package com.beyondx.java;
import org.junit.Test;
public class WrapperTest {
// 基本数据类型, 包装类 -> String
@Test
public void test5() {
int num1 = 10;
String str1 = num1 + "";
}
}
1.2. 现在的做法
基本数据类型, 包装类 -> String, 调用 String重载的 valueOf(Xxx xxx)
package com.beyondx.java;
import org.junit.Test;
public class WrapperTest {
@Test
public void test6() {
// 1.基本数据类型 -> String
float f = 12.3f;
String str1 = String.valueOf(f);
System.out.println(str1);
// 2.包装类 -> String
Double d = new Double(12.4);
String str2 = String.valueOf(d);
System.out.println(str2);
}
}
java.lang.String部分源码
public final class String implements java.io.Serializable, Comparable<String>, CharSequence {
// 很多构造器
public String() {
}
public String(String original) {}
public String(char value[]) {}
public String(char value[], int offset, int count) {}
public String(int[] codePoints, int offset, int count) {}
public String(byte ascii[], int hibyte, int offset, int count) {}
public String(byte ascii[], int hibyte) {}
public String(byte bytes[], int offset, int length, String charsetName) {}
public String(byte bytes[], int offset, int length, Charset charset) {}
public String(byte bytes[], String charsetName) {}
public String(byte bytes[], Charset charset) {}
public String(byte bytes[], int offset, int length) {}
public String(byte bytes[]) {}
public String(StringBuffer buffer) {}
public String(StringBuilder builder) {}
public static String valueOf(Object obj) {}
public static String valueOf(char data[]) {}
public static String valueOf(char data[], int offset, int count) {}
public static String valueOf(boolean b) {}
public static String valueOf(char c) {}
public static String valueOf(int i) {}
public static String valueOf(long l) {}
public static String valueOf(float f) {}
public static String valueOf(double d) {}
}
2. String -> 基本数据类型, 包装类
String -> 基本数据类型, 包装类, 调用包装类的 parseXxx(String s)
package com.beyondx.java;
import org.junit.test;
public class WrapperTest {
@Test
public void test6() {
String str1 = "123";
int num = Integer.parseInt(str1);
System.out.println(num + 1);
String str2 = "true";
boolean b1 = Boolean.parseBoolean(str2);
System.out.println(b1);
}
}
java.lang.Integer部分源码
public final class Integer extends Number implements Comparable<Integer> {
// 一些方法
public static int parseInt(String s, int radix) throws NumberFormatException {}
public static int parseInt(String s) throws NumberFormatException {}
public static int parseUnsignedInt(String s, int radix) throws NumberFormatException {}
public static int parseUnsignedInt(String s) throws NumberFormatException {}
}
参考链接