Udemy logo

java string to integerIntroduction to Strings

Java is an objected-oriented high level programming language. It is widely used in the industry for building complex projects and systems. It contains a lot of primitive data types to handle data including integer, double and float. It also provides two powerful classes namely String and StringBuffer. The String class consists of string objects that are a combination of characters, which are used to manipulate string characters. These objects cannot be changed. They are immutable and read only. The StringBuffer is a class that is mutable and can be easily changed using append statement.

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

Learn more about Java programming by taking a class at Udemy.com

The following code shows you how to create a string object in Java:

String abc=“Hello World”
StringBuffer str1= new StringBuffer(“Hello I am Buffer”)
str1.append(“Yes You can change Me”);

“String” is a keyword and “abc” is a variable name. Whenever a String literal is encountered, the compiler creates a String object and stores the value in it. Java provides many functions for string manipulations. A few frequently used ones are:

String input is often taken from the user to perform manipulations. The advantage the string class provides is that you can easily convert strings to other forms of data types like an integer or float. A String does not have a range to save values, and therefore any length of values can be saved.

Though different classes like integer, float and double are present individually, the string is preferred to store values and then convert them in the respective forms as needed. This provides the programmer the flexibility to use values in all forms.

There are two ways to convert Strings to numbers.

Using the valueOf() function: This is a static method used for string to numeric conversions. Every numeric subclasses for primitive data types (integer, float, double, short) have a class method called “valueOf” that converts a 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 a string");
// 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));
}
}

The above code compiles to the following program:

Input: Enter a string

Output

The SUM is 12.33

Difference is 7.7299995

Multiplication is 23.068998

Division is 4.3608694

Learn Java programming from scratch at Udemy.com

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 a string");
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 a string

10

20

Output:

The SUM is 30

Difference is -10

The string is taken as input from the user and stored in a variable. This variable is then passed to the static function “valueOf()” to convert into an integer, float and double respectively. An important point to note is that if the string cannot be parsed, then a NumberFormatException error is thrown at runtime by the function.

Using parse methods: This is another method used to convert a number from a string using the parse method of numeric subclasses for primitive data type class. This is a more flexible way for string to numeric conversions. This method also gives a NumberFormatException error when the string provided is not in the proper numeric form. The function takes a single parameter in the form of a string and returns the equivalent integer, double and float value respectively. It is a static method. No objects are 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 a 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 taken from the user and written inside the “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”

Learn more about Java programming by taking a class at Udemy.com

In the above example, the string is passed directly to the Integer.parseInt function and the result obtained was the required integer, double and float number respectively. Also, the input from the user is retrieved and converted to numbers. Note the user input written inside the try catch block. The reason is if the string entered by the user cannot be parsed by the method, then the exception is thrown and displayed on the screen by the catch method.

Conclusion

String conversion to a numeric data type is a good approach in places where you have to deal with large values. It’s not very reliable to use string conversions in programs where direct use of the primitive data type can be done.

Page Last Updated: May 2014

Top courses in Java

Develop Minecraft Plugins (Java)
Stephen King
4.8 (3,666)
Bestseller
Java SE 11 Developer 1Z0-819 OCP Course - Part 1
Tim Buchalka, Tim Buchalka's Learn Programming Academy
4.4 (3,804)
Bestseller
Java Programming for Complete Beginners
in28Minutes Official
4.5 (40,531)
The Complete Java Certification Course
Job Ready Programmer
4.5 (26,156)
Java for Absolute Beginners
Nick H
4.6 (7,749)
Learn Selenium with Java, Cucumber + Live Project
Pavan Kumar
4.6 (5,072)
Bestseller
Java for Beginners
Navin Reddy
4.6 (767)

More Java Courses

Java students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.

Request a demo