当前位置: 移动技术网 > IT编程>开发语言>Java > 浅述int与string类型转换的两种方法

浅述int与string类型转换的两种方法

2019年07月22日  | 移动技术网IT编程  | 我要评论

具体详情如下所示:

int -> string
int i=12345;
string s="";

第一种方法:s=i+"";

第二种方法:s=string.valueof(i);

这两种方法有什么区别呢?作用是不是一样的呢?是不是在任何下都能互换呢?

string -> int
s="12345";
int i;

第一种方法: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) 相当于 new integer(integer.parseint(s)),也会抛异常,但会多产生一个对象

--------------------------------------------------------------------

1如何将字串 string 转换成整数 int?

a. 有两个方法:

1). int i = integer.parseint([string]); 或

i = integer.parseint([string],[int radix]);

2). int i = integer.valueof(my_str).intvalue();

注: 字串转成 double, float, long 的方法大同小异.

2 如何将整数 int 转换成字串 string ?

a. 有叁种方法:

1.) string s = string.valueof(i);

2.) string s = integer.tostring(i);

3.) string s = "" + i;

注: double, float, long 转成字串的方法大同小异.

java数据类型转换

这是一个例子,说的是java中数据数型的转换.供大家学习

package shenmixiaozhu;
import java.sql.date;
public class typechange {
public typechange() {
}
//change the string type to the int type
public static int stringtoint(string intstr)
{
integer integer;
integer = integer.valueof(intstr);
return integer.intvalue();
}
//change int type to the string type
public static string inttostring(int value)
{
integer integer = new integer(value);
return integer.tostring();
}
//change the string type to the float type
public static float stringtofloat(string floatstr)
{
float floatee;
floatee = float.valueof(floatstr);
return floatee.floatvalue();
}
//change the float type to the string type
public static string floattostring(float value)
{
float floatee = new float(value);
return floatee.tostring();
}
//change the string type to the sqldate type
public static java.sql.date stringtodate(string datestr)
{
return java.sql.date.valueof(datestr);
}
//change the sqldate type to the string type
public static string datetostring(java.sql.date datee)
{
return datee.tostring();
}
public static void main(string[] args)
{
java.sql.date day ;
day = typechange.stringtodate("2003-11-3");
string strday = typechange.datetostring(day);
system.out.println(strday);
}
}

以上内容是小编给大家介绍的int与string类型转换的两种方法,希望能够帮助到大家。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网