String to Integer Conversion in Java

Java has lot of primitive data type to handle data of all sorts like integer, double and float and two powerful classes, String and StringBuffer, therefore conversion among the data types  like String to Integer or vice versa becomes essential part in Java Programming.

String class of java is most commonly used for any manipulation, calculations and storing user data. Strings class in java has string objects, which are combination of characters including numbers and punctuations

Creating strings is easy: String abc=“Hello World”

“String” is a keyword here and “abc” is a variable name. Whenever the String literal is encountered the compiler creates a String object and stores the value in it.
Java provides many functional for string manipulation. Few frequently used ones are:

length():Returns the length of the string.
toUpperCase(): Converts the string to upper case.
ToLowerCase(): Converts the string to lower case.
Trim(): Removes all the white spaces from the string.
Substring(): Helps to extract the portion of the string from large string

Strings inputs are often taken from the user to perform manipulations. The advantage that the string class provides is that we can easily convert strings to other form of data types for instance integer or float. String does not have a range to save value. Any length of values can be saved.
Though different class like integer, float and double are present individually, the string is preferred to store the values and then convert them in the respective forms as needed. This provides the programmer the flexibility to use values in all forms and as needed. The string values can be converted to integer, float and double data types.

There are two ways to convert Strings to numbers.

Using valueOf() Function: This is the static method used for string to numeric conversion. Every numeric subclasses of primitive data types (integer, float, double, short) have a class method called “valueOf” that converts the string object to the particular data type.

Syntax:

int a=Integer.valueOf(“123”);
double b=Double.valueOf(“12334.442”);
float f=Float.valueOf(“10.23”);

Example of String to Float Conversion:

class ValueOfDemo {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String str1,str2;
System.out.println("Enter the strings");

// Taking String input from the user
str1=sc.nextLine();
str2=sc.nextLine();

// String conversion to the float
float a = (Float.valueOf(str1));
float b = (Float.valueOf(str2));

// Printing the values
System.out.println("The SUM is " +
(a + b));
System.out.println("Difference is " +
(a - b));
System.out.println("Multiplication is " +
(a * b));
System.out.println("Division is " +
(a / b));

}
}
Input: Enter the strings

Output
The SUM is 12.33
Difference is 7.7299995
Multiplication is 23.068998
Division is 4.3608694


String to Integer conversion:

class IntDemo {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String str1,str2;
System.out.println("Enter the strings");
str1=sc.nextLine();
str2=sc.nextLine();
// String to Integer conversions
int a = (Integer.valueOf(str1));
int b = (Integer.valueOf(str2));

// Printing the integer value
System.out.println("The SUM is " +
(a + b));
System.out.println("Difference is " +
(a - b));

}
}

Input: Enter the strings
10
20
Output:

The SUM is 30
Difference is -10

The string is taken as input from the user and stored in a variable. These variable is then passed to static function “valuOf()” to convert in to integer ,float and double respectively. The important point to note is if the string cannot be parsed than NumberFormatException exception is thrown at run time by the function.

Using parse methods: This is another way of conversion from string to number using the parse method of numeric subclasses of primitive data type class. This is more flexible way of string to numeric conversion. This method also gives NumberFormatException when string provided is not in proper numeric form. The function takes single parameter in form of string and returns equivalent integer, double and float value respectively. It is static method i.e. no objects is needed to call the class.

Syntax:

int i=Integer.parseInt(“1245”);
double b=Double.parseDouble(“1234.8978”);

Example Program:

class ValueOfDemo {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String str1,str2;
System.out.println("Enter the string");
str1=sc.nextLine();
// String passed is converted to Integer
int ab=Integer.parseInt(“1000”);
System.out.println("I am Integer" +ab);

// String passed is converted to Double

double d=Double.parseDouble("2.332");

// String passed is converted to Float

float f=Float.parseFloat("2.33");

System.out.println("I am Double " +d);
System.out.println("I am Float"+f);
// Input is been taken from the userTherefore written inside try catch block to handle NumberFormatException.

try
{
int ca=Integer.parseInt("str1");
System.out.println("I am Integer" +ca);
}
catch(Exception e)
{
System.out.println("Exception is "+e);

}

}
}
Input:
Enter the string
00000013212dsd

Output:
I am Integer 100
I am Double 2.332
I am Float 2.33
Exception is java.lang.NumberFormatException: For input string: "str1"

In the above example, we have passed the string directly into the Integer.parseInt function and the result obtained us was the required integer, double and float number respectively. Also the input from the user is taken to convert the input in to numbers. Note user input written inside the try catch block. The reason is if the string entered by the user cannot be parsed by the method than the exception will be thrown that would be displayed on the screen by the catch method.

Conclusion
String conversion to numeric is good approach in the places where very large values are required to deal with. It is not very reliable to use string conversion in programs where direct use of the primitive data type can be done. parseXYZ() methods are used when taking input from the user since we do not know what the user would enter. It increases overhead to deal with inputs if user enter null value or invalid numeric data .

Leave a Reply

Your email address will not be published. Required fields are marked *