Java String字符串和整型int的相互转换
string类型转换成int类型
String
字符串转整型 int
有以下两种方式:
目前我们只需要知道Integer
是 int
基本数据类型的封装类就行。
Integer.parseInt(str)
下面我们来贴代码转换一下:
public class text {
public static void main(String[] args) {
String pride="123";
int n =0;
n =Integer.parseInt(pride);
System.out.println(pride);
}
}
Integer.valueOf(str).intValue()
public class text {
public static void main(String[] args) {
String pride="123";
int n =0;
n =Integer.valueOf(pride).intValue();
System.out.println(pride);
}
}
int类型转换成string类型
整型 int
转 String
字符串类型有以下 3 种方法:
String s = String.valueOf(i);
public class text {
public static void main(String[] args) {
int b=132;
String H=String.valueOf(b);
System.out.println(H);
}
}
String s = Integer.toString(i);
public class text {
public static void main(String[] args) {
int b=132;
String H= Integer.toString(b);
System.out.println(H);
}
}
String s = “” + i;
public class text {
public static void main(String[] args) {
int b=132;
String H=b+"";
System.out.println(H);
}
}
使用第三种方法相对第一第二种耗时比较大。在使用第一种 valueOf()
方法时,注意 valueOf
括号中的值不能为空,否则会报空指针异常。