String and int Conversion in JAVA
Category Programming Techniques
1 How to convert a string String to an integer int?
A. There are two methods:
int i = Integer.parseInt([String]);
ori = Integer.parseInt([String],[int radix]);
int i = Integer.valueOf(my_str).intValue();
Note: The method to convert a string to Double, Float, Long is similar.
2 How to convert an integer int to a string String?
A. There are three methods:
String s = String.valueOf(i);
String s = Integer.toString(i);
String s = "" + i;
Note: The method to convert Double, Float, Long to a string is similar.
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? Do they have the same effect? 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? Do they have the same effect? Can they be interchanged in any situation?
Here are the answers:
First method: s=i+""; //Creates two String objects
Second method: s=String.valueOf(i); //Uses the static method of the String class, creating only one object
First method: i=Integer.parseInt(s);
//Uses the static method directly, does not create extra objects, but throws an exception
Second method: i=Integer.valueOf(s).intValue();
//Integer.valueOf(s) is equivalent to new Integer(Integer.parseInt(s)), also throws an exception, but creates an extra object
Java Data Type Conversion
This is an example of data type conversion in JAVA. It is provided for everyone's learning and reference.
Example
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);
}
}