在Java的简单应用中,经常会涉及到各种变量类型之间的相互转换问题,尤其以Int,string和char三种类型为常见,
所以特别从网上进行参考,结合自己的理解和认知,对这些变量转换进行了一个总结和实例输出,以方便理解和
记忆。
部分参考出自:http://blog.csdn.net/lisa0220/article/details/6649707
1、String转化为int类型
String mystr = "123";
(1)int i = Integer.valueOf(mystr).intValue(); //先将string转化为Integer,然后再转换为int类型
System.out.println("mystr = " + i);
(2)int j = Integer.parseInt(mystr); //直接将string转化为int类型
System.out.println("mystr = " + j);
输出:
注:string转化为Integer的方法:Integer integer = Integer.valueOf(mystr);
Integer转化为string的方法:Integer integer = new Integer(10); String str = integer.toString();
2、int转化为String类型
int i = 123;
(1)String mystr = String.valueOf(i); //使用String类的求值方法
System.out.println("mystr = " + mystr);
(2)String mystr1 = Integer.toString(i); //使用Integer类的求值方法
System.out.println("mystr1 = " + mystr1);
(3)String mystr2 = i + ""; //在原先Int类型基础上添加空白字符,这种方法会将int类型的i先
// 转换为string类型,然后加上空白符,最终形成string
System.out.println("mystr2 = " + mystr2);
输出:
注:int类型和Integer类型之间互相转换
Integer integer = new Integer(i);
int num = Integer.intValue();
3、char转化为string类型
String mystr = "123";
char[] ch = mystr.toCharArray();
for(int i=0; i<ch.length; i++)
System.out.println("ch["+i+"]=" + ch[i]);
输出:
4、string转化为char类型
char a = '1';
String mystr1 = String.valueOf(a);
System.out.println("mystr1 = "+ mystr1);
输出:
5、int转化为char类型
int n = 1;
char a = (char)(n+'0');
System.out.println("a = " + a);
输出:
6、char转化为int类型
char a = '1';
int n = a - '0';
System.out.println("n = " + n);
输出: