Converting Strings to Integers in Java
Submitted by GeePee on Tuesday, May 12, 2015 - 23:16.
There are times when it is necessary to accept input as a string, yet you may need to take a value from that string and convert it into an integer for calculations. This is a very common practice in Java programming. It is especially useful in string arrays, when certain containers are meant to hold numbers, and they are needed for calculations.
We perform this variable conversion with the following line of code:
An integer may also be converted into a string. This is somewhat less common, but worth learning at the same time. An instance where this may be used is converting an integer value string so that it may be stored inside a string array. Here is the code for converting an integer value into a string.
int i = Integer.parseInt(s);
Where i is the new integer being declared, and s is the string variable that already has a value. Below is a short example program demonstrating this:
- import java.util.Scanner;
- public class strtoint
- {
- {
- i = i * 2;
- }
- }
String s = String.valueOf(i);
Where s is the string being declared, and i is the integer which you wish to convert.
As you can see, it is quite simple to convert both ways. I challenge you to try it out to convert a string array value into an integer, preform a calculation on it, and then put it back into the array. If there are any questions, let me know in the comments below.
Add new comment
- 15 views