How to Change an Integer to a String in Java
When you enter a number into a text box on a web page, the browser recognizes that number as a string. Computers cannot perform computations using strings. For instance, a Java program cannot add the string "12" to the string "4" without converting both strings to numbers. Java supports multiple types of numbers including floating points and integers. To ensure that your Java application runs correctly, convert all strings to integers or other numeric types before using them in calculations.
Instructions
-
-
1
Open your Java editor and create a new project. Create an empty class named "TestConversion" and add the following code to it:
public static void main(String[] args) {
int number1;
int number2;
int sum;
String stringNumber1 = "5";
String stringNumber2 = "2";
}
This creates two integer variables, number1 and number2. It also creates and initializes the string variables, stringNumber1 and stringNumber2.
-
2
Add the following code below the previous code:
try
{
number1 = Integer.parseInt(stringNumber1);
number2 = Integer.parseInt(stringNumber2);
sum = number1 + number2;
System.out.println("Sum of number1 + number2 = " + sum);
}
catch (NumberFormatException exception)
{
System.out.println("NumberFormatException: " + exception.getMessage());
}
This code uses Java's "parseInt" function to convert the strings to integers and store them in the integer variables. The "try" and "catch" statements perform exception handling and display an error message if the string-to-integer conversion fails.
-
-
3
Compile the code and run the project. See the message "Sum of number1 + number2 = 7" after Java converts the strings to integers.
-
1
Tips & Warnings
Java also has a parseFloat function that converts strings to floating-point numbers. Use the parseInt function to convert strings into integers instead of floating-point numbers whenever possible. Floating-point numbers are large than integers and consume more memory.
References
Resources
- Photo Credit numbers image by Amer Delibasic from Fotolia.com