convert string to int java

Learn Java Programming for Beginners

There are Two methods to convert String to integer,first is Using Integer.parseInt() and other is without using Integer.parseInt() method.

Method 1:

In this method i am using Integer.parseInt(),this method is simple to use and easy to understand.

import java.io.*;

class stringtoint

{

public static void main(String args[])throws IOException

{

int integer1;

String String1;

DataInputStream in=new DataInputStream(System.in);

System.out.print("Enter String to convert into int\t");

String1=in.readLine();

integer1=Integer.parseInt(String1);

System.out.print("Converted String‚ to int \t"+integer1);

}

}

Method 2

In method 2 i will first convert string into ascii numbers ,then this numbers are converted into integer value.

import java.io.*;

class stringtoint

{

public static void main(String args[])throws IOException

{

int integer1,integer2,integer3=0,j=1;

String String1;

DataInputStream in=new DataInputStream(System.in);

System.out.print("Enter String to convert into int\t");

String1=in.readLine();

for(int i=String1.length()-1;i>=0;i--)

{

integer1=String1.charAt(i); //converting String to ascii number

integer2=Character.getNumericValue(integer1); //converting ascii number to integer

integer3=integer3+integer2*j;  //adding converted integers

j=j*10;

}

System.out.print("Converted String‚ to int \t"+integer3);

}

}

OUTPUT FOR BOTH PROGRAMS:

Enter String to convert into int   123

Converted String to int 123

You may also like...

Leave a Reply

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