Java string to int conversion
This article demonstrates how to convert a string that contains a number value to an integer in Java.
Tutorial info:
| Name: | Java string to int conversion |
| Total steps: | 1 |
| Category: | Basics |
| Date: | 2011-04-08 |
| Level: | Beginner |
| Product: | See complete product |
| Viewed: | 4638 |
Bookmark Java string to int conversion
Step 1 - Converting Java string to int
Java string to int conversion
Beginner Java programmers quite often ask the question how to convert a number that is stored in a String variable to a basic int variable or to an Integer object. Fortunately this is a quite simple task using the parseInt or valueOf static methods of the Integer class. Let’s see the following situation, when the string is converted to a primitive int value:
String s = "123";
int i = Integer.parseInt(s);
// Now print out the resultSystem.out.println("Original string: " + s);
System.out.println("The int value: " + i);
As you can see it is really simple. In cases when you want an Integer object instead of the primitive type you can use the following code:
String s = "123";
Integer iO = Integer.valueOf(s);
// Now print out the resultSystem.out.println("Original string: " + s);
System.out.println("The Integer value: " + iO);
Sometimes it can happen that the string can not be converted to int as it contains some space characters. In this case simply use trim() to remove them as below. The zeros before the number cause no problem in the conversion.
String s = " 000123";
int i = Integer.parseInt(s.trim());
// Now print out the resultSystem.out.println("Original string: " + s);
System.out.println("The int value: " + i);
So that simple is the string to int conversion in Java.
Tags: java string to int conversion, string to int, java string conversion, string integer conversion
| Java string to int conversion - Table of contents |
|---|
| Step 1 - Converting Java string to int |