Convert String to Int in Java

Converting a string variable to an integer variable in Java is easy. There are actually two different approaches, both equally simply. Below is an example of both approaches, with both use the same string variable to output to various integer variables.

String myVariable = “12345″;

Approach 1:
int approach1 = Integer.parseInt(myVariable);

Approach 2:
int approach2 = Integer.valueOf(myVariable);

If you have any opinion on why you use one approach over the other, let the community know!

Share and Enjoy:
  • Digg
  • DotNetKicks
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Live
  • MySpace
  • Netvibes
  • Reddit
  • StumbleUpon
You can leave a response, or trackback from your own site.

4 Responses to “Convert String to Int in Java”

  1. Nishant says:

    Atleast write the headings properly. Its not converting String to Int, its the other way round.

  2. aravind says:

    public int IsInteger(string data)
    {
    bool result = true;

    try
    {
    int.Parse(data);
    }
    catch (FormatException)
    {
    result = false;
    }

    return result;

    }

    ex:how the code should look:

    previous code:
    scanf(“%d”,x) should be changed into

    new code:
    where x is a string now
    where y is bool
    where x is a int

    do
    {
    //get the interger value
    scanf(“%s”,x)

    //use the function above to find wheather the given value is int or not.
    y=IsInteger(x)

    //if y is true i.e int then convert it into interger using atoi function.
    if(y)
    {
    z=atoi(z);
    }
    else
    {
    printf(“error msg”);

    //if false then scan the variable again
    }while(!y)

  3. nice information for me. thank you very much with that info.

Leave a Reply