String与int相互转换

字串String转换成整数 int

String -> int
s="12345";
int i;
第一种方法:i=Integer.parseInt(s);          //直接使用静态方法,不会产生多余的对象,但会抛出异常
第二种方法:i=Integer.valueOf(s).intValue(); //Integer.valueOf(s) 相当于 new Integer(Integer.parseInt(s)),也会抛异常,但会多产生一个对象




整数 int 转换成字串 String 

int -> String
1.) String s = String.valueOf(i);
2.) String s = Integer.toString(i);
3.) String s = "" + i;
s="12345";
int i;
第一种方法:s=String.valueOf(i); //直接使用String类的静态方法,只产生一个对象
第三种方法:s=i+"";    //会产生两个String对象
注: Double, Float, Long 转成字串的方法大同小异.

猜你喜欢

转载自blog.csdn.net/qq_39471933/article/details/80909064