JAVA中String、char和int类型转换

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhangvalue/article/details/85002072

int -> String

int i=12345;
String s="";
第一种方法:s=i+""; //会产生两个String对象
第二种方法:s=String.valueOf(i);//直接使用String类的静态方法,只产生一个对象

第三种方法:String s = Integer.toString(i);

String s = "123";
try {
    int i = Integer.valueOf(s).intValue()
} catch (NumberFormatException e) {
    e.printStackTrace();
}

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

String -> int

s="12345";
int i;

//直接使用静态方法,不会产生多余的对象,但会抛出异常
第一种方法:i=Integer.parseInt(s);

//Integer.valueOf(s) 相当于 new Integer(Integer.parseInt(s)),也会抛异常,但会多产生一个对象
第二种方法:i=Integer.valueOf(s).intValue();
 

String s= "123";
try {
    int i = Integer.parseInt(s);
} catch (NumberFormatException e) {
    e.printStackTrace();
}

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

String -> char 将一个字符串String 转换成一个字符数组

String str = "abcde";
char[] ca=str.toCharArray();
-----------------------------------------------------------------------------
char -> String
String s=ca.toString();      //任何类型都可以采用toString()转换成String类型

运算符-取整,取绝对值,取余数

  1. 舍掉小数取整:Math.floor(3.5)=3
  2. 四舍五入取整:Math.rint(3.5)=4
  3. 进位取整:Math.ceil(3.1)=4 
  4. 取绝对值:Math.abs(-3.5)=3.5
  5. 取余数:A%B = 余数 

猜你喜欢

转载自blog.csdn.net/zhangvalue/article/details/85002072