1 How to convert a String to an int?
A. There are two methods:
- 1、 int i = Integer.parseInt([String]);ori = Integer.parseInt([String],[int radix]);
- 2、 int i = Integer.valueOf(my_str).intValue();
Note: The methods for converting strings to Double, Float, and Long are essentially the same.
2 How to convert an int to a String?
A. There are three methods:
- 1、String s = String.valueOf(i);
- 2、String s = Integer.toString(i);
- 3、String s = "" + i;
Note: The methods for converting Double, Float, and Long to strings are essentially the same.
int -> String
int i=12345;
String s="";
First method:s=i+"";
Second method:s=String.valueOf(i);
What is the difference between these two methods? Are their functions the same? Can they be interchanged in any situation?
String -> int
s="12345";
int i;
First method:i=Integer.parseInt(s);
Second method:i=Integer.valueOf(s).intValue();
What is the difference between these two methods? Are their functions the same? Can they be interchanged in any situation?
The following is the answer:
First method:s=i+""; // This will create two String objects
Second method:s=String.valueOf(i);// Directly using the static method of the String class creates only one object
First method:i=Integer.parseInt(s);// Directly using the static method does not create extra objects, but it will throw an exception
Second method:i=Integer.valueOf(s).intValue();//Integer.valueOf(s) is equivalent to new Integer(Integer.parseInt(s)); it also throws an exception but creates one additional object.
Java data type conversion
This is an example about data type conversion in Java, for everyone to learn and reference.