Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Java-conversion Convert a String into an Integer Data

Related Tutorials


 
 

Share on Google+Share on Google+

Convert a String into an Integer Data

Advertisement
In this section, you will learn to convert a string type data into an integer type.

Convert a String into an Integer Data

     

In this section, you will learn to convert a string type data into an integer type. The java.lang package provides the functionality to convert the string type data into an integer type data.

Code Description:

This program takes a string type data on the console and converts it into an integer. Data at the console is as a string type so, it must be converted into an integer type using the parseInt() method. This method converts the string type number into an integer format. Whenever you give the string type data as 's' then the exception must be thrown. 

parseInt():
The parseInt() method parses the string parameter as a signed decimal integer. This method is used to convert an integer type data into a string type data.

Here is the  code of  this code:

import java.io.*;
import java.lang.*;

public class  StringToInt{
  public static void main(String[] args)throws IOException {
  BufferedReader bf = new BufferedReader(
    new 
InputStreamReader(System.in));
  System.out.println("Enter an integer number: ");
  String str = bf.readLine();
  int i = Integer.parseInt(str);
  System.out.println("String: " + str);
  System.out.println("Integer: " + i);
  }
}

In the above program we have prompted the user to enter the a String and then reads the data using the code:

bf.readLine();

Then we have used the Integer.parseInt(str) method to convert it into int value.

Advertisement

If you run the program you will find the following output.

Output this program.

C:\vinod\convert>javac StringToInt.java

C:\vinod\convert>java StringToInt
Enter an integer number:
10
String: 10
Integer: 10

Download this program

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 15, 2007

Related Tutorials

Discuss: Convert a String into an Integer Data   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com