Join the Stack Overflow Community
Stack Overflow is a community of 6.3 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

How can I convert a String to an int in Java?

My String contains only numbers and I want to return the number it represents.

For example, given the string "1234" the result should be the number 1234.

share|improve this question

23 Answers 23

up vote 2622 down vote accepted
int foo = Integer.parseInt("1234");

See the Java Documentation for more information.

(If you have it in a StringBuilder (or the ancient StringBuffer), you'll need to do Integer.parseInt(myBuilderOrBuffer.toString()); instead).

share|improve this answer
42  
Back in the C++ days, we could call static methods from an instance. So people saw all the methods available on a class by looking at an instance of one. Now we have to reference the type to get the list of static methods. And thus code-self-documentation falls one step back into obscurity. – Lee Louviere May 3 '13 at 18:08
53  
@LeeLouviere You can do this in Java with non-primitive types, just like in C++. – Overv Dec 10 '13 at 18:21
12  
@LeeLouviere I don't really think that's a feature, so much as something that can hamper your first-glance understanding of the class. – davidahines Dec 22 '14 at 16:27
13  
This will throw NumberFormatException if input is not a valid number. – Francesco Menzani Aug 28 '15 at 16:05
20  
Should be: (If you have it in a StringBuffer, your code is ancient and you need to use StringBuilder). – bcsb1001 Aug 31 '15 at 11:40

For example, here are two ways:

Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);

There is a slight difference between these methods:

  • valueOf returns a new or cached instance of java.lang.Integer
  • parseInt returns primitive int.

The same is for all cases: Short.valueOf/parseShort, Long.valueOf/parseLong, etc.

share|improve this answer
48  
For the differences between the two methods, see this question – hertzsprung May 19 '13 at 8:38
8  
valueOf method is just return valueOf(parseInt(string)); – Paul Verest Oct 28 '14 at 8:55

Well, a very important point to consider is that the Integer parser throws NumberFormatException as stated in Javadoc.

int foo;
String StringThatCouldBeANumberOrNot = "26263Hello"; //will throw exception
String StringThatCouldBeANumberOrNot2 = "26263"; //will not throw exception
try {
      foo = Integer.parseInt(StringThatCouldBeANumberOrNot);
} catch (NumberFormatException e) {
      //Will Throw exception!
      //do something! anything to handle the exception.
}

try {
      foo = Integer.parseInt(StringThatCouldBeANumberOrNot2);
} catch (NumberFormatException e) {
      //No problem this time, but still it is good practice to care about exceptions.
      //Never trust user input :)
      //Do something! Anything to handle the exception.
}

It is important to handle this exception when trying to get integer values from split arguments or dynamically parsing something.

share|improve this answer

Do it manually:

public static int strToInt( String str ){
    int i = 0;
    int num = 0;
    boolean isNeg = false;

    //Check for negative sign; if it's there, set the isNeg flag
    if (str.charAt(0) == '-') {
        isNeg = true;
        i = 1;
    }

    //Process each character of the string;
    while( i < str.length()) {
        num *= 10;
        num += str.charAt(i++) - '0'; //Minus the ASCII code of '0' to get the value of the charAt(i++).
    }

    if (isNeg)
        num = -num;
    return num;
}
share|improve this answer
11  
What if the input is greater than 2^32? What if the input contains non-numeric characters? – yohm Oct 22 '14 at 3:43
19  
One of the things a programmer must learn on joining the workforce, if not before, is never to re-invent wheels. This may be a fun exercise, but don't expect your code to pass code review if you do this kind of thing in a commercial setting. – David Wallace Jan 1 at 4:16
    
@yohm those are special case; you can handle with long and some regex; however, by then you can use parseInt. – Billz Jan 1 at 5:18
12  
Why in the world is there a python answer on a Java question!? – John Hascall Mar 4 at 22:02
2  
-1 Sorry, but this is a pretty poor algorithm, with lots of limitations, no error handling, and some weird anomalies (eg "" gives an exception, "-" will produce 0, and "+" produces -5). Why would anyone choose this over Integer.parseInt(s)? - I see the point about this being an interview question, but a) that doesn't imply you'd do it this way (which is what the questioner asked), and b) this answer's a pretty bad example anyway. – SusanW Jul 28 at 17:27

Currently I'm doing an assignment for college, where I can't use certain expressions, such as the ones above, and by looking at the ASCII table, I managed to do it. It's a far more complex code , but it could help others that are restricted like I was.

The first thing to do is to receive the input, in this case, a String of digits, I'll call it String number, and in this case, I'll exemplify it using the number 12, therefore String number = "12";

Another limitation was the fact that I couldn't use repetitive cicles, therefore, a for cicle (which would have been perfect) can't be used either. This limits us a bit, but then again, that's the goal. Since I only needed two digits (taking the last two digits), a simple charAtsolved it:

 //Obtaining the integer values of the char 1 and 2 in ASCII
 int semilastdigitASCII = number.charAt(number.length()-2);  
 int lastdigitASCII = number.charAt(number.length()-1);

Having the codes, we just need to look up at the table, and make the necessary adjustments:

 double semilastdigit = semilastdigitASCII - 48;  //A quick look, and -48 is the key
 double lastdigit = lastdigitASCII - 48;

Now, why double? Well, because of a really "weird" step. Currently we have two doubles, 1 and 2, but we need to turn it into 12, there isn't any mathematic operation that we can do. What we're doing is divide the latter (lastdigit) by 10, in this fashion 2/10 = 0.2 (hence why double) like this:

 lastdigit = lastdigit/10;

This is merely playing with numbers. What we did here was turning the last digit into a decimal. But now, look at what happens:

 double jointdigits = semilastdigit + lastdigit; // 1.0 + 0.2 = 1.2

Without getting too into the math, we're simply isolating units the digits of a number. You see, since we only consider 0-9, dividing by a multiple of 10 is like creating a "box" where you store it (think back at when your first grade teacher explained you what a unit and a hundred were). So:

 int finalnumber = (int) (jointdigits*10); //Be sure to use parentheses "()"

And there you go, you turned a String of digits (in this case, two digits), into an integer composed of those two digits, considering the following limitations:

  • No Repetitive Cicles
  • No "Magic" Expressions such as parseInt
share|improve this answer
3  
Using type double for parsing an integer is not only a bad idea performance-wise. Values like 0.2 are periodic numbers in floating-point representation and cannot be represented precisely. Try System.out.println(0.1+0.2) to see the point -- the result will not be 0.3! Better stick with library code whereever you can, in this case Integer.parseInt(). – ChrisB Aug 14 '15 at 14:23
5  
It’s not clear what kind of problem this answer tries to solve, first, why anyone should ever have that restriction you describe, second, why you have to look at an ASCII table as you can simply use '0' for the character instead of 48 and never have to bother with its actual numeric value. Third, the entire detour with double values makes no sense at all as you are dividing by ten, just to multiply with ten afterwards. The result simply is semilastdigit * 10 + lastdigit as learnt in elementary school, when the decimal system was introduced… – Holger Mar 4 at 10:47
    
@Holger I was personally given that restriction when first starting out programming, and also when I had to write (pen/paper) similar interactions in a test. It's uncommon, but it's a method that is easily understood and while not being the most efficient by miles it's a method that works decently enough for small projects. SO.SE is meant to help everyone, not just a few. I provided an alternative method, for those who are starting out by learning how to create a pseudo-algorithm and turning it into an algorithm rather than using premade java expressions. Although I did forget that '0' is cool – Oak May 2 at 8:49

An alternate solution is to use Apache Commons' NumberUtils:

int num = NumberUtils.toInt("1234");

The Apache utility is nice because if the string is an invalid number format then 0 is always returned. Hence saving you the try catch block.

Apache NumberUtils API Version 3.4

share|improve this answer
4  
You rarely want 0 to be used when an invalid number is parsed. – wnoise Mar 22 at 15:18
1  
Zero is what java uses as a default if an int field on an object is not set. So in that regards it makes sense. – Ryboflavin Apr 19 at 18:42

Converting a string to an int is more complicated than just convertig a number. You have think about the following issues:

  • Does the string only contains numbers 0-9?
  • What's up with -/+ before or after the string? Is that possible (referring to accounting numbers)?
  • What's up with MAX_-/MIN_INFINITY? What will happen if the string is 99999999999999999999? Can the machine treat this string as an int?
share|improve this answer
    
Yes - and there's a nasty edge case around -2^31. If you try negating 2^31, you might run into difficulties...... – SusanW Oct 5 at 22:52

I'm have a solution, but I do not know how effective it is. But it works well, and I think you could improve it. On the other hand, I did a couple of tests with JUnit which step correctly. I attached the function and testing:

static public Integer str2Int(String str) {
    Integer result = null;
    if (null == str || 0 == str.length()) {
        return null;
    }
    try {
        result = Integer.parseInt(str);
    } 
    catch (NumberFormatException e) {
        String negativeMode = "";
        if(str.indexOf('-') != -1)
            negativeMode = "-";
        str = str.replaceAll("-", "" );
        if (str.indexOf('.') != -1) {
            str = str.substring(0, str.indexOf('.'));
            if (str.length() == 0) {
                return (Integer)0;
            }
        }
        String strNum = str.replaceAll("[^\\d]", "" );
        if (0 == strNum.length()) {
            return null;
        }
        result = Integer.parseInt(negativeMode + strNum);
    }
    return result;
}

Testing with JUnit:

@Test
public void testStr2Int() {
    assertEquals("is numeric", (Integer)(-5), Helper.str2Int("-5"));
    assertEquals("is numeric", (Integer)50, Helper.str2Int("50.00"));
    assertEquals("is numeric", (Integer)20, Helper.str2Int("$ 20.90"));
    assertEquals("is numeric", (Integer)5, Helper.str2Int(" 5.321"));
    assertEquals("is numeric", (Integer)1000, Helper.str2Int("1,000.50"));
    assertEquals("is numeric", (Integer)0, Helper.str2Int("0.50"));
    assertEquals("is numeric", (Integer)0, Helper.str2Int(".50"));
    assertEquals("is numeric", (Integer)0, Helper.str2Int("-.10"));
    assertEquals("is numeric", (Integer)Integer.MAX_VALUE, Helper.str2Int(""+Integer.MAX_VALUE));
    assertEquals("is numeric", (Integer)Integer.MIN_VALUE, Helper.str2Int(""+Integer.MIN_VALUE));
    assertEquals("Not
     is numeric", null, Helper.str2Int("czv.,xcvsa"));
    /**
     * Dynamic test
     */
    for(Integer num = 0; num < 1000; num++) {
        for(int spaces = 1; spaces < 6; spaces++) {
            String numStr = String.format("%0"+spaces+"d", num);
            Integer numNeg = num * -1;
            assertEquals(numStr + ": is numeric", num, Helper.str2Int(numStr));
            assertEquals(numNeg + ": is numeric", numNeg, Helper.str2Int("- " + numStr));
        }
    }
}
share|improve this answer

We can use the parseInt(String str) method of the Integer wrapper class for converting a String value to an integer value.

For example:

String strValue = "12345";
Integer intValue = Integer.parseInt(strVal);

The Integer class also provides the valueOf(String str) method:

String strValue = "12345";
Integer intValue = Integer.valueOf(strValue);

We can also use toInt(String strValue) of NumberUtils Utility Class for the conversion:

String strValue = "12345";
Integer intValue = NumberUtils.toInt(strValue);
share|improve this answer

Integer.decode

You can also use public static Integer decode(String nm) throws NumberFormatException.

It also works for base 8 and 16:

// base 10
Integer.parseInt("12");     // 12 - int
Integer.valueOf("12");      // 12 - Integer
Integer.decode("12");       // 12 - Integer
// base 8
// 10 (0,1,...,7,10,11,12)
Integer.parseInt("12", 8);  // 10 - int
Integer.valueOf("12", 8);   // 10 - Integer
Integer.decode("012");      // 10 - Integer
// base 16
// 18 (0,1,...,F,10,11,12)
Integer.parseInt("12",16);  // 18 - int
Integer.valueOf("12",16);   // 18 - Integer
Integer.decode("#12");      // 18 - Integer
Integer.decode("0x12");     // 18 - Integer
Integer.decode("0X12");     // 18 - Integer
// base 2
Integer.parseInt("11",2);   // 3 - int
Integer.valueOf("11",2);    // 3 - Integer

If you want to get int instead of Integer you can use:

  1. Unboxing:

    int val = Integer.decode("12"); 
    
  2. intValue():

    Integer.decode("12").intValue();
    
share|improve this answer

Whenever there is the slightest possibility that the given String does not contain an Integer, you have to handle this special case. Sadly, the standard Java methods Integer::parseInt and Integer::valueOf throw a NumberFormatException to signal this special case. Thus, you have to use exceptions for flow control, which is generally considered bad coding style.

In my opinion, this special case should be handled by returning an Optional<Integer>. Since Java does not offer such a method, I use the following wrapper:

private Optional<Integer> tryParseInteger(String string) {
    try {
        return Optional.of(Integer.valueOf(string));
    } catch (NumberFormatException e) {
        return Optional.empty();
    }
}

Usage:

// prints 1234
System.out.println(tryParseInteger("1234").orElse(-1));
// prints -1
System.out.println(tryParseInteger("foobar").orElse(-1));

While this is still using exceptions for flow control internally, the usage code becomes very clean.

share|improve this answer

You can also begin by removing all non numerical characters and then parsing the int:

string mystr = mystr.replaceAll( "[^\\d]", "" );
int number= Integer.parseInt(mystr);

But be warned that this only works for non negative numbers.

share|improve this answer
12  
This will cause -42 to be parsed as 42. – user289086 Oct 11 '14 at 14:00
5  
Yeah, this only works for non negative numbers which are correct to begin with and hence, don’t need this replacement step. For every other case, this attempt to automatically fix it, will make things worse (as almost every attempt to automatically fix something). If I pass in "4+2", I’ll get 42 as a result without any hint about that what I tried to do was misguided. The user will get the impression that entering basic expressions like 4+2 was a valid input, but the application continues with a wrong value. Besides that, the type is String, not string – Holger Mar 4 at 11:01
    
Or change first line to--> string mystr = mystr.replaceAll( "[^\\d\\-]", "" ); – apm Aug 19 at 10:57

You can use this code also, with some precautions.

  • Option #1: Handle the exception explicitly, for example, showing a message dialog and then stop the execution of the current workflow. For example:

    try
        {
            String stringValue = "1234";
    
            // From String to Integer
            int integerValue = Integer.valueOf(stringValue);
    
            // Or
            int integerValue = Integer.ParseInt(stringValue);
    
            // Now from integer to back into string
            stringValue = String.valueOf(integerValue);
        }
    catch (NumberFormatException ex) {
        //JOptionPane.showMessageDialog(frame, "Invalid input string!");
        System.out.println("Invalid input string!");
        return;
    }
    
  • Option #2: Reset the affected variable if the execution flow can continue in case of an exception. For example, with some modifications in the catch block

    catch (NumberFormatException ex) {
        integerValue = 0;
    }
    

Using a string constant for comparison or any sort of computing is always a good idea, because a constant never returns a null value.

share|improve this answer
2  
Putting JOptionPane.showMessageDialog() in the answer to vanilla Java question makes no sense. – John Hascall Mar 4 at 22:05
    
Integer.valueOf(String); does not return type int. – php_coder_3809625 Apr 26 at 23:54

Guava has tryParse(String), which returns null if the string couldn't be parsed, for example:

Integer fooInt = Ints.tryParse(fooString);
if (fooInt != null) {
  ...
}
share|improve this answer

As mentioned Apache Commons NumberUtils can do it. Which return 0 if it cannot convert string to int.

You can also define your own default value.

NumberUtils.toInt(String str, int defaultValue)

example:

NumberUtils.toInt("3244", 1) = 3244
NumberUtils.toInt("", 1)     = 1
NumberUtils.toInt(null, 5)   = 5
NumberUtils.toInt("Hi", 6)   = 6
NumberUtils.toInt(" 32 ", 1) = 1 //space in numbers are not allowed
NumberUtils.toInt(StringUtils.trimToEmpty( "  32 ",1)) = 32; 
share|improve this answer

Apart from these above answers, I would like to add several functions:

    public static int parseIntOrDefault(String value, int defaultValue) {
    int result = defaultValue;
    try {
      result = Integer.parseInt(value);
    } catch (Exception e) {

    }
    return result;
  }

  public static int parseIntOrDefault(String value, int beginIndex, int defaultValue) {
    int result = defaultValue;
    try {
      String stringValue = value.substring(beginIndex);
      result = Integer.parseInt(stringValue);
    } catch (Exception e) {

    }
    return result;
  }

  public static int parseIntOrDefault(String value, int beginIndex, int endIndex, int defaultValue) {
    int result = defaultValue;
    try {
      String stringValue = value.substring(beginIndex, endIndex);
      result = Integer.parseInt(stringValue);
    } catch (Exception e) {

    }
    return result;
  }

And here are results while you running them:

  public static void main(String[] args) {
    System.out.println(parseIntOrDefault("123", 0)); // 123
    System.out.println(parseIntOrDefault("aaa", 0)); // 0
    System.out.println(parseIntOrDefault("aaa456", 3, 0)); // 456
    System.out.println(parseIntOrDefault("aaa789bbb", 3, 6, 0)); // 789
  }
share|improve this answer

For normal string you can use:

int number = Integer.parseInt("1234");

For String builder and String buffer you can use:

Integer.parseInt(myBuilderOrBuffer.toString());
share|improve this answer

Just for fun. You can use java 8 Optional for converting a String into anInteger.

String str = "123"; 
Integer value = Optional.of(str).map(Integer::valueOf).get();
// will return Integer value of specified String, or it
// will throw NPE when str is null.     
value = Optional.ofNullable(str).map(Integer::valueOf).orElse(-1);
// will do the same as the code above, except it will return -1 
// when srt is null, instead of throwing a NPE.

We just combine here Integer.valueOf and Optinal. Probably there might be situations when this is useful - for example when you want to avoid null checks. Pre java 8 code will look like this:

Integer value = (str == null) ? -1 : Integer.parseInt(str);
share|improve this answer
String str="1234";

int foo=Integer.parseInt("1234");

make sure there is no non-numeric data in the string.

For example, here are two ways:

   Integer x = Integer.valueOf(str);
    // or
   int y = Integer.parseInt(str);
share|improve this answer
String s="100";
try {
 int i=Integer.parseInt( s );
}catch( Exception e ) {
 System.out.println(e.getMessage());
}



String s="100L";
try {
  int i=Integer.parseInt( s );
 }catch( Exception e ) {
  System.out.println(e.getMessage());
}
share|improve this answer
1  
your answer certainly is worth a little explanation. Help us add searchable content to make SO even better. – J. Chomel Sep 3 at 16:57

you need to use parseInt for

int value = Integer.parseInt("123"); 
share|improve this answer
String st = "123";

int num = Integer.parseInt(st);
share|improve this answer
   int i = 0; // Initializing an integer.
   try{
       i = yourTextField.getText();
   }catch(NumberFormatException ex){
       // message or yourTextField.setText(<Message>);
   }
share|improve this answer
4  
Add some clarification to your answer instead of just posting a code snippet. Answers like these tend to get down-voted and/or deleted. – Marko Popovic May 5 at 7:32
1  
Er... sorry, this won't even compile. "incompatible types: String cannot be converted to int". – S.L. Barth May 5 at 8:12
    
i = yourTextField.getText(); is not correct – Venkat Sep 30 at 11:10

protected by Gilbert Le Blanc May 18 '13 at 14:35

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.