java type of conversion (String float int)

This change several types of equipment, usually used parseInt (), parseFloat (), valueof () method, but this is different.

Look at their different return types

  1. static int parseInt (String s)
    the string argument as a signed decimal integer analyzed.
  2. static Integer valueOf (int i)
    Returns Integer instance representing a specified int value.
  3. static Integer valueOf (String s)
    Returns Integer String object values specified retention.

String —>int

Integer class requires the parseInt () method or valueOf () method for conversion.
For example:

String str = "123";
try {
    int a = Integer.parseInt(str);
} catch (NumberFormatException e) {
    e.printStackTrace();
}
String str = "123";
try {
    int b = Integer.valueOf(str).intValue()
    //int b = Integer.valueOf(str)
    //这样也可以
} catch (NumberFormatException e) {
    e.printStackTrace();
}

Why try-catch it! ! !

  • Because the conversion process needs attention, since there may be non-numeric string, so when the conversion need to capture handle exceptions or throw this exception

int—>String

int i=12345;
第一种方法:String s=i+"";
第二种方法:String s=String.valueOf(i);
第三种方法:String s=Integer.toString(i);

please explain:

  • The return value from the difference between them can be seen that the parseInt () returns an int and substantially valueOf () returns the packaging Integer

  • Integer object method can be used and the type int and Object types can not be converted to each other

  • Integer.parseInt (China) The return value is an int, but will be reported anomaly, because the parameter values ​​of non-

  • Integer.valueOf (chuan) return value is of type Integer. The Integer assigned to int type, then, JRE can do this yourself


Similar conversion String and a float.

Reference links
.

Published 175 original articles · won praise 76 · Views 230,000 +

Guess you like

Origin blog.csdn.net/qq_29232943/article/details/52811176