Java string to int conversion


Home - Tutorials - Basics

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:13585

Bookmark Java string to int conversion



AddThis Social Bookmark Button

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:

Code:
  1. String s = "123";
  2. int i = Integer.parseInt(s);
  3. // Now print out the result
  4. System.out.println("Original string: " + s);
  5. 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:

Code:
  1. String s = "123";
  2. Integer iO = Integer.valueOf(s);
  3. // Now print out the result
  4. System.out.println("Original string: " + s);
  5. 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.

Code:
  1. String s = "    000123";
  2. int i = Integer.parseInt(s.trim());
  3. // Now print out the result
  4. System.out.println("Original string: " + s);
  5. 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



Total time: 0.1643