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.

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); } }