浅述int与string类型转换的两种方法
具体详情如下所示:
int->String inti=12345; Strings="";
第一种方法:s=i+"";
第二种方法:s=String.valueOf(i);
这两种方法有什么区别呢?作用是不是一样的呢?是不是在任何下都能互换呢?
String->int s="12345"; inti;
第一种方法:i=Integer.parseInt(s);
第二种方法:i=Integer.valueOf(s).intValue();
这两种方法有什么区别呢?作用是不是一样的呢?是不是在任何下都能互换呢?
以下是答案:
第一种方法:s=i+"";//会产生两个String对象
第二种方法:s=String.valueOf(i);//直接使用String类的静态方法,只产生一个对象
第一种方法:i=Integer.parseInt(s);//直接使用静态方法,不会产生多余的对象,但会抛出异常
第二种方法:i=Integer.valueOf(s).intValue();//Integer.valueOf(s)相当于newInteger(Integer.parseInt(s)),也会抛异常,但会多产生一个对象
--------------------------------------------------------------------
1如何将字串String转换成整数int?
A.有两个方法:
1).inti=Integer.parseInt([String]);或
i=Integer.parseInt([String],[intradix]);
2).inti=Integer.valueOf(my_str).intValue();
注:字串转成Double,Float,Long的方法大同小异.
2如何将整数int转换成字串String?
A.有叁种方法:
1.)Strings=String.valueOf(i);
2.)Strings=Integer.toString(i);
3.)Strings=""+i;
注:Double,Float,Long转成字串的方法大同小异.
JAVA数据类型转换
这是一个例子,说的是JAVA中数据数型的转换.供大家学习
packageshenmixiaozhu;
importjava.sql.Date;
publicclassTypeChange{
publicTypeChange(){
}
//changethestringtypetotheinttype
publicstaticintstringToInt(Stringintstr)
{
Integerinteger;
integer=Integer.valueOf(intstr);
returninteger.intValue();
}
//changeinttypetothestringtype
publicstaticStringintToString(intvalue)
{
Integerinteger=newInteger(value);
returninteger.toString();
}
//changethestringtypetothefloattype
publicstaticfloatstringToFloat(Stringfloatstr)
{
Floatfloatee;
floatee=Float.valueOf(floatstr);
returnfloatee.floatValue();
}
//changethefloattypetothestringtype
publicstaticStringfloatToString(floatvalue)
{
Floatfloatee=newFloat(value);
returnfloatee.toString();
}
//changethestringtypetothesqlDatetype
publicstaticjava.sql.DatestringToDate(StringdateStr)
{
returnjava.sql.Date.valueOf(dateStr);
}
//changethesqlDatetypetothestringtype
publicstaticStringdateToString(java.sql.Datedatee)
{
returndatee.toString();
}
publicstaticvoidmain(String[]args)
{
java.sql.Dateday;
day=TypeChange.stringToDate("2003-11-3");
Stringstrday=TypeChange.dateToString(day);
System.out.println(strday);
}
}
以上内容是小编给大家介绍的int与string类型转换的两种方法,希望能够帮助到大家。