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

Go To StackoverFlow.com

2732

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.

2011-04-07 18:27
by Unknown user


3787

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

If you look at the Java Documentation you'll notice the "catch" is that this function can throw a NumberFormatException, which of course you have to handle:

int foo;
try {
   foo = Integer.parseInt(myString);
}
catch (NumberFormatException e)
{
   foo = 0;
}

(This treatment defaults a malformed number to 0, but you can do something else if you like.)

Alternatively, you can use an Ints method from the Guava library, which in combination with Java 8's Optional, makes for a powerful and concise way to convert a string into an int:

import com.google.common.primitives.Ints;

int foo = Optional.ofNullable(myString)
 .map(Ints::tryParse)
 .orElse(0)
2011-04-07 18:29
by Rob Hruska
This will throw <code>NumberFormatException</code> if input is not a valid number - Francesco Menzani 2015-08-28 16:05
In addition to catching a NumberFormatException, the user should also be careful about the length of the strings they're passing in; if they're long enough to overflow an integer, they might want to consider using Long::parseLong instead - Allison 2018-01-17 09:37
@Allison especially if using BIGINT field in a PostgreSQL auto incremented primary key field for instance. Much safer to use lon - Letholdrus 2018-01-22 19:18
You could check if the string is a Number first: https://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-numeric-in-jav - JPRLCol 2018-01-25 20:17
This method also throws exception when string is not a parsable integer in base 10. Use overloaded method to work in other bases. e.g. Integer.parseInt("1001", 8); for base 8. Source - lokesh 2018-08-08 11:00
If you use Integer.parseInt prepare to put it inside a try catch block since this will throw are NumberFormat or InputMismatch Exception if it is not a valid number. Then in that case have proper exception handling at the catch block level. Otherwise as mentioned below you can also use the Integer class and then convert it to int - Radioactive 2018-10-26 15:50


629

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.

2011-04-07 18:36
by smas
For the differences between the two methods, see this questionhertzsprung 2013-05-19 08:38
valueOf method is just return valueOf(parseInt(string));Paul Verest 2014-10-28 08:55
@PaulVerest i dont get it... valueOf calls itself recursively - user463035818 2018-09-03 12:44
@user463035818 valueOf has two overloads - for int and String. valueOf(String) is implemented by first parsing the String to an int using parseInt(String) and then wrapping that int in an Integer by using valueOf(int). No recursion here because valueOf(String) and valueOf(int) are two completely different functions, even if they have the same name - PhilipRoman 2018-10-31 16:45
@PhilipRoman thanks for the clarification - user463035818 2018-10-31 17:14


230

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.

2013-04-30 06:54
by Ali Akdurak
how can I parse "26263Hello" ? I want to extract 26263 in that cas - user463035818 2018-05-16 08:01
@user463035818 - See https://docs.oracle.com/javase/8/docs/api/java/util/regex/package-summary.html - a regular expresssion pattern of "([0-9]+)" will "capture" the first sequence of one or more digits one through nine. Look at the Matcher class in that package - Mark Stewart 2018-06-08 16:16


83

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;
}
2013-09-11 02:08
by Billz
What if the input is greater than 2^32? What if the input contains non-numeric characters - yohm 2014-10-22 03:43
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 - Dawood ibn Kareem 2016-01-01 04:16
@yohm those are special case; you can handle with long and some regex; however, by then you can use parseInt - Billz 2016-01-01 05:18
-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 2016-07-28 17:27
I suppose this answer is for curious fellows.. - Timur Milovanov 2018-06-19 12:50


42

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 cycles, therefore, a for cycle (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.

We're dividing the latter (lastdigit) by 10 in the fashion 2/10 = 0.2 (hence why double) like this:

 lastdigit = lastdigit/10;

This is merely playing with numbers. We were 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 cycles
  • No "Magic" Expressions such as parseInt
2014-03-20 23:51
by Oak
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 2015-08-14 14:23
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 2016-03-04 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 coo - Oak 2016-05-02 08:49


40

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

2015-08-27 12:07
by Ryboflavin
You rarely want 0 to be used when an invalid number is parsed - wnoise 2016-03-22 15:18
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 2016-04-19 18:42
@Ryboflavin No, it doesn't. One of those is a well-defined language semantic, and the other is an exceptio - etherous 2017-06-01 22:25


32

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();
    
2016-03-07 00:42
by ROMANIA_engineer
Finally! Someone who actually bother to post the results/output of the conversions! Can you also add some with "-" signs - not2qubit 2017-04-27 11:42


25

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.

2016-04-04 03:13
by Stefan Dollase


23

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?
2013-10-20 13:18
by Dennis Ahaus
Yes - and there's a nasty edge case around -2^31. If you try negating 2^31, you might run into difficulties..... - SusanW 2016-10-05 22:52


22

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);
2015-10-20 09:51
by Giridhar Kumar


22

Methods to do that:

 1. Integer.parseInt(s)
 2. Integer.parseInt(s, radix)
 3. Integer.parseInt(s, beginIndex, endIndex, radix)
 4. Integer.parseUnsignedInt(s)
 5. Integer.parseUnsignedInt(s, radix)
 6. Integer.parseUnsignedInt(s, beginIndex, endIndex, radix)
 7. Integer.valueOf(s)
 8. Integer.valueOf(s, radix)
 9. Integer.decode(s)
 10. NumberUtils.toInt(s)
 11. NumberUtils.toInt(s, defaultValue)

Integer.valueOf produces Integer object, all other methods - primitive int.

Last 2 methods from commons-lang3 and big article about converting here.

2017-10-03 19:16
by Dmytro Shvechikov


19

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));
        }
    }
}
2014-05-23 15:38
by fitorec
You can do it simpler: (int) Double.parseDouble(input.replaceAll("[^0-9\\.\\-]", ""));Dávid Horváth 2018-11-13 09:53


19

Use Integer.parseInt(yourString)

Remember following things:

Integer.parseInt("1"); // ok

Integer.parseInt("-1"); // ok

Integer.parseInt("+1"); // ok

Integer.parseInt(" 1"); // Exception (blank space)

Integer.parseInt("2147483648"); // Exception (Integer is limited to a maximum value of 2,147,483,647)

Integer.parseInt("1.1"); // Exception (. or , or whatever is not allowed)

Integer.parseInt(""); // Exception (not 0 or something)

There is only one type of exception: NumberFormatException

2017-10-06 19:00
by Lukas Bauer
Does the int maximum value here also give a NumberFormatException - The Coding Wombat 2018-10-24 16:02
No, the maximum value is stil oka - Lukas Bauer 2018-11-24 15:02


17

Just for fun: You can use Java 8's Optional for converting a String into an Integer:

String str = "123";
Integer value = Optional.of(str).map(Integer::valueOf).get();
// Will return the integer value of the specified string, or it
// will throw an 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 an NPE.

Here we just combine 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);
2016-11-09 11:34
by Anton Balaniuc
If you ask me, it throws a NFE if you deliver an invalid Integer string .. - KarelG 2017-02-20 10:19
@KarelG Yes, it does. This code above is useless - Dorian Gray 2017-08-25 21:23
return -1 in case of null looks really strange...what if I want to parse "-1" string - Dmytro Shvechikov 2018-08-07 08:47


16

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

Integer fooInt = Ints.tryParse(fooString);
if (fooInt != null) {
  ...
}
2016-08-06 17:56
by Vitalii Fedorenko


14

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.

2013-10-20 13:11
by Thijser
This will cause -42 to be parsed as 42 - NoName 2014-10-11 14:00
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 2016-03-04 11:01
Or change first line to--> string mystr = mystr.replaceAll( "[^\d\-]", "" ) - apm 2016-08-19 10:57
@Holger If I saw someone write this at work, I'd move them off my team. It would fail review with a fairly major blast radius. There's virtually no case where it does the Right Thing: it produces unexpected, weird, "WTF" results. Please, nobody do this - SusanW 2017-03-22 08:42


12

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
  }
2016-08-01 14:44
by nxhoaf


9

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.

2015-12-31 05:28
by manikant gautam
Putting JOptionPane.showMessageDialog() in the answer to vanilla Java question makes no sense - John Hascall 2016-03-04 22:05
Integer.valueOf(String); does not return type int - php_coder_3809625 2016-04-26 23:54


9

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; 
2016-07-26 05:26
by Alireza Fattahi


9

You can use new Scanner("1244").nextInt(). Or ask if even an int exists: new Scanner("1244").hasNextInt()

2017-02-28 20:36
by Christian Ullenboom


9

In programming competitions, where you're assured that number will always be a valid integer, then you can write your own method to parse input. This will skip all validation related code (since you don't need any of that) and will be a bit more efficient.

  1. For valid positive integer:

    private static int parseInt(String str) {
        int i, n = 0;
    
        for (i = 0; i < str.length(); i++) {
            n *= 10;
            n += str.charAt(i) - 48;
        }
        return n;
    }
    
  2. For both positive and negative integers:

    private static int parseInt(String str) {
        int i=0, n=0, sign=1;
        if(str.charAt(0) == '-') {
            i=1;
            sign=-1;
        }
        for(; i<str.length(); i++) {
            n*=10;
            n+=str.charAt(i)-48;
        }
        return sign*n;
    }
    

     

  3. If you are expecting a whitespace before or after these numbers, then make sure to do a str = str.trim() before processing further.

2017-04-24 05:36
by Raman Sahasi


7

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

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

2016-04-20 09:54
by iKing
This is exactly the same as the select answer - Steve Smith 2017-06-14 11:15
There is no value to the site, in repeating an answer that someone else posted FIVE YEARS before you - Dawood ibn Kareem 2017-10-29 18:28


7

For normal string you can use:

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

For String builder and String buffer you can use:

Integer.parseInt(myBuilderOrBuffer.toString());
2016-08-18 07:07
by Aditya


7

Simply you can try this:

  • Use Integer.parseInt(your_string); to convert a String to int
  • Use Double.parseDouble(your_string); to convert a String to double

Example

String str = "8955";
int q = Integer.parseInt(str);
System.out.println("Output>>> " + q); // Output: 8955

String str = "89.55";
double q = Double.parseDouble(str);
System.out.println("Output>>> " + q); // Output: 89.55
2017-09-14 19:45
by Vishal Yadav
This answer doesn't appear to add anything beyond the answers recommending Integer.parseInt posted a few years earlier (converting String to double would be a different question) - Dukeling 2017-12-30 19:43


6

Here we go

String str="1234";
int number = Integer.parseInt(str);
print number;//1234
2016-11-20 04:24
by Shivanandam


6

I am a little bit surprised that nobody didn't mention Integer constructor that takes String as a parameter.
So, here is:

String myString = "1234";
int i1 = new Integer(myString);

Java 8 - Integer(String).

Of course, the constructor will return type Integer, and unboxing operation converts value to int.


It's important to mention
This constructor calls parseInt method.

public Integer(String var1) throws NumberFormatException {
    this.value = parseInt(var1, 10);
}
2018-04-23 20:49
by djm.im


5

One method is parseInt(String) returns a primitive int

String number = "10";
int result = Integer.parseInt(number);
System.out.println(result);

Second method is valueOf(String) returns a new Integer() object.

String number = "10";
Integer result = Integer.valueOf(number);
System.out.println(result);
2017-08-12 14:25
by Pankaj Mandale


5

Use Integer.parseInt() and put it inside a try...catch block to handle any errors just in case a non-numeric character is entered, for example,

private void ConvertToInt(){
    String string = txtString.getText();
    try{
        int integerValue=Integer.parseInt(string);
        System.out.println(integerValue);
    }
    catch(Exception e){
       JOptionPane.showMessageDialog(
         "Error converting string to integer\n" + e.toString,
         "Error",
         JOptionPane.ERROR_MESSAGE);
    }
 }
2017-11-11 01:58
by David


4

This is Complete program with all conditions positive, negative without using library

import java.util.Scanner;


    public class StringToInt {
     public static void main(String args[]) {
      String inputString;
      Scanner s = new Scanner(System.in);
      inputString = s.nextLine();

      if (!inputString.matches("([+-]?([0-9]*[.])?[0-9]+)")) {
       System.out.println("Not a Number");
      } else {
       Double result2 = getNumber(inputString);
       System.out.println("result = " + result2);
      }

     }
     public static Double getNumber(String number) {
      Double result = 0.0;
      Double beforeDecimal = 0.0;
      Double afterDecimal = 0.0;
      Double afterDecimalCount = 0.0;
      int signBit = 1;
      boolean flag = false;

      int count = number.length();
      if (number.charAt(0) == '-') {
       signBit = -1;
       flag = true;
      } else if (number.charAt(0) == '+') {
       flag = true;
      }
      for (int i = 0; i < count; i++) {
       if (flag && i == 0) {
        continue;

       }
       if (afterDecimalCount == 0.0) {
        if (number.charAt(i) - '.' == 0) {
         afterDecimalCount++;
        } else {
         beforeDecimal = beforeDecimal * 10 + (number.charAt(i) - '0');
        }

       } else {
        afterDecimal = afterDecimal * 10 + number.charAt(i) - ('0');
        afterDecimalCount = afterDecimalCount * 10;
       }
      }
      if (afterDecimalCount != 0.0) {
       afterDecimal = afterDecimal / afterDecimalCount;
       result = beforeDecimal + afterDecimal;
      } else {
       result = beforeDecimal;
      }

      return result * signBit;
     }
    }
2017-09-01 06:53
by Anup Gupta
There is no need to reinvent the wheel, just use Integer.parseInt - Dorian Gray 2017-11-10 11:38
@TobiasWeimer yes, we can do but this is without using librar - Anup Gupta 2017-11-11 05:38
I can see that, but what is the point not to use a library - Dorian Gray 2017-11-11 08:15
@TobiasWeimer, some people need this how to do without using Library - Anup Gupta 2017-11-11 14:26
No, no one needs it because it is a function inside the JDK, not some third party plugin - Dorian Gray 2017-11-11 15:00


3

By the way, be aware that if the string is null, the call:

int i = Integer.parseInt(null);

throws NumberFormatException, not NullPointerException.

2018-06-20 21:26
by Pavel Molchanov


3

Can be done in 5 ways:

import com.google.common.primitives.Ints;
import org.apache.commons.lang.math.NumberUtils;

1) Using Ints.tryParse:

String number = "999";
int result = Ints.tryParse(number);

2) Using NumberUtils.createInteger:

String number = "999";
Integer result = NumberUtils.createInteger(number);

3) Using NumberUtils.toInt:

String number = "999";
int result = NumberUtils.toInt(number);

4) Using Integer.valueOf:

String number = "999";
Integer result = Integer.valueOf(number);

5) Using Integer.parseInt:

String number = "999";
int result = Integer.parseInt(number);
2018-09-12 09:07
by Santosh Jadi
NumberUtils handles null and empty scenarios as well - Sundararaj Govindasamy 2019-02-05 16:24


3

Integer.parseInt(myString); - using wrapper class

2018-11-29 13:44
by Phani Kumar


2

import java.util.*;

public class strToint{

    public static void main(String[] args){

            String str = "123";

            byte barr[] = str.getBytes();

            System.out.println(Arrays.toString(barr));
            int result=0;
            for(int i=0;i<barr.length;i++){
                    //System.out.print(barr[i]+" ");
                    int ii = barr[i];
                    char a = (char)ii;
                    int no = Character.getNumericValue(a);
                    result=result*10+no;
                    System.out.println(result);

            }
            System.out.println("result:"+result);
    }

}

2018-12-25 10:33
by Abhijeet Kale


2

You could use any of followings:

  1. Integer.parseInt(s)
  2. Integer.parseInt(s, radix)
  3. Integer.parseInt(s, beginIndex, endIndex, radix)
  4. Integer.parseUnsignedInt(s)
  5. Integer.parseUnsignedInt(s, radix)
  6. Integer.parseUnsignedInt(s, beginIndex, endIndex, radix)
  7. Integer.valueOf(s)
  8. Integer.valueOf(s, radix)
  9. Integer.decode(s)
  10. NumberUtils.toInt(s)
  11. NumberUtils.toInt(s, defaultValue)
2019-02-11 13:15
by Rajeev Ranjan


1

public static int parseInt(String s)throws NumberFormatException

you can user Integer.parseInt() to convert a String to int.

convert a String 20 to an primitive int.

    String n = "20";
    int r = Integer.parseInt(n);//returns a primitive int       
    System.out.println(r);

Output-20

if the string does not contain a parsable integer. it will thrown NumberFormatException

String n = "20I";// throwns NumberFormatException
int r = Integer.parseInt(n);
System.out.println(r);

public static Integer valueOf(String s)throws NumberFormatException

you can use Integer.valueOf(), in this it will returns an Integer object.

String n = "20";
Integer r = Integer.valueOf(n); //returns a new Integer() object.   
System.out.println(r);

Output-20

References https://docs.oracle.com/en/

2018-07-27 08:45
by Poorna Senani Gamage


0

Use Integer.parseInt(), this will help you in parsing your string value to int.

Example:

String str = "2017";
int i = Integer.parseInt(str);
System.out.println(i);

output: 2017

2018-08-22 06:54
by Alekya


0

Convert a string to an integer with the parseInt method of the Java Integer class. The parseInt method is to convert the String to an int and throws a NumberFormatException if the string cannot be converted to an int type.

Overlooking the exception it can throw, use this:

int i = Integer.parseInt(myString);

If the String signified by the variable myString is a valid integer like “1234”, “200”, “1”, and it will be converted to a Java int. If it fails for any reason, the change can throw a NumberFormatException, so the code should be a little longer to account for this.

Ex. Java String to int conversion method, control for a possible NumberFormatException

public class JavaStringToIntExample
{
  public static void main (String[] args)
  {
    // String s = "test";  // use this if you want to test the exception below
    String s = "1234";

    try
    {
      // the String to int conversion happens here
      int i = Integer.parseInt(s.trim());

      // print out the value after the conversion
      System.out.println("int i = " + i);
    }
    catch (NumberFormatException nfe)
    {
      System.out.println("NumberFormatException: " + nfe.getMessage());
    }
  }
}

If the change attempt fails – in case, if you can try to convert the Java String test to an int — the Integer parseInt process will throw a NumberFormatException, which you must handle in a try/catch block.

2018-11-09 15:24
by Nisarg


0

You can use parseInt method

  String SrNumber="5790";
int extractNumber = Integer.parseInt(SrNumber);
System.out.println(extractNumber);//Result will be --5790
2019-01-14 08:03
by Sunil Dhappadhule


0

I wrote this fast method to parse a string input into int or long. It is faster than the current JDK 11 Integer.parseInt or Long.parseLong. Although, you only asked for int, I also included the long parser. The code parser below requires that the parser's method must be small for it to operate quickly. An alternative version is below the test code. The alternative version is pretty quick and it does not depend on the size of the class.

This class check for overflow and you could customize the code to adapt to your needs. An empty string will yield 0 with my method but that is intentional. You can change that to adapt your case or use as is.

This is only the part of the class where parseInt and parseLong are needed. Note that this only deal with base 10 numbers.

The test code for the int parser is below the code below.

/*
 * Copyright 2019 Khang Hoang Nguyen
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 * @author: Khang Hoang Nguyen - kevin@fai.host.
 **/
final class faiNumber{        
    private static final long[] longpow = {0L, 1L, 10L, 100L, 1000L, 10000L, 100000L, 1000000L, 10000000L, 100000000L, 1000000000L,
                                           10000000000L, 100000000000L, 1000000000000L, 10000000000000L, 100000000000000L,
                                           1000000000000000L, 10000000000000000L, 100000000000000000L, 1000000000000000000L,
                                           };

    private static final int[] intpow = { 0, 1, 10, 100, 1000, 10000,
                                          100000, 1000000, 10000000, 100000000, 1000000000 
                                        };

    /**
     * parseLong(String str) parse a String into Long. 
     * All errors throw by this method is NumberFormatException.
     * Better errors can be made to tailor to each use case.
     **/
    public static long parseLong(final String str) { 
        final int length = str.length();
        if ( length == 0 ) return 0L;        

        char c1 = str.charAt(0); int start;

        if ( c1 == '-' || c1 == '+' ){
            if ( length == 1 ) throw new NumberFormatException( String.format("Not a valid long value. Input '%s'.", str) );
            start = 1;
        } else {
            start = 0;
        }
        /*
         * Note: if length > 19, possible scenario is to run through the string 
         * to check whether the string contains only valid digits.
         * If the check had only valid digits then a negative sign meant underflow, else, overflow.
         */
        if ( length - start > 19 ) throw new NumberFormatException( String.format("Not a valid long value. Input '%s'.", str) );

        long c; 
        long out = 0L;

        for ( ; start < length; start++){
            c = (str.charAt(start) ^ '0');
            if ( c > 9L ) throw new NumberFormatException( String.format("Not a valid long value. Input '%s'.", str) );
            out += c * longpow[length - start];
        }

        if ( c1 == '-' ){
            out = ~out + 1L;
            // if out > 0 number underflow(supposed to be negative).
            if ( out > 0L ) throw new NumberFormatException( String.format("Not a valid long value. Input '%s'.", str) );
            return out;
        }
        // if out < 0 number overflow(supposed to be positive).
        if ( out < 0L ) throw new NumberFormatException( String.format("Not a valid long value. Input '%s'.", str) );
        return out;
    }

    /**
     * parseInt(String str) parse a string into an int.
     * return 0 if string is empty. 
     **/
    public static int parseInt(final String str) { 
        final int length = str.length();
        if ( length == 0 ) return 0;        

        char c1 = str.charAt(0); int start; 

        if ( c1 == '-' || c1 == '+' ){
            if ( length == 1 ) throw new NumberFormatException( String.format("Not a valid integer value. Input '%s'.", str) );
            start = 1;
        } else {
            start = 0;
        }

        int out = 0; int c;
        int runlen = length - start;

        if ( runlen > 9 ) {
            if ( runlen > 10 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );

            c = (str.charAt(start) ^ '0');   // <- Any number from 0 - 255 ^ 48 will yield greater than 9 except 48 - 57
            if ( c > 9 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
            if ( c > 2 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
            out += c * intpow[length - start++];
        }

        for ( ; start < length; start++){
            c = (str.charAt(start) ^ '0');
            if ( c > 9 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
            out += c * intpow[length - start];
        }

        if ( c1 == '-' ){
            out = ~out + 1;
            if ( out > 0 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
            return out;
        }

        if ( out < 0 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
        return out;
    }
}

Test Code Section. This should take around 200 seconds or so.

// Int Number Parser Test;
long start = System.currentTimeMillis();    
System.out.println("INT PARSER TEST");
for (int i = Integer.MIN_VALUE; i != Integer.MAX_VALUE; i++){
   if( faiNumber.parseInt(""+i) != i ) System.out.println("Wrong");
   if ( i == 0 ) System.out.println("HalfWay Done");
}

if( faiNumber.parseInt(""+Integer.MAX_VALUE) != Integer.MAX_VALUE ) System.out.println("Wrong");
long end = System.currentTimeMillis();
long result = (end - start);
System.out.println(result);        
// INT PARSER END */

An alternative method which is also very fast. Note that array of int pow is not used but a mathematical optimization of multiply by 10 by bit shifting.

public static int parseInt(final String str) { 
    final int length = str.length();
    if ( length == 0 ) return 0;        

    char c1 = str.charAt(0); int start; 

    if ( c1 == '-' || c1 == '+' ){
        if ( length == 1 ) throw new NumberFormatException( String.format("Not a valid integer value. Input '%s'.", str) );
        start = 1;
    } else {
        start = 0;
    }

    int out = 0; int c;
    while( start < length && str.charAt(start) == '0' ) start++; // <-- This to disregard leading 0, can be removed if you know exactly your source does not have leading zeroes.
    int runlen = length - start;

    if ( runlen > 9 ) {
        if ( runlen > 10 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );

        c = (str.charAt(start++) ^ '0');   // <- Any number from 0 - 255 ^ 48 will yield greater than 9 except 48 - 57
        if ( c > 9 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
        if ( c > 2 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
        out = (out << 1) + (out << 3) + c; // <- alternatively this can just be out = c or c above can just be out;
    }

    for ( ; start < length; start++){
        c = (str.charAt(start) ^ '0');
        if ( c > 9 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
        out = (out << 1) + (out << 3) + c; 
    }

    if ( c1 == '-' ){
        out = ~out + 1;
        if ( out > 0 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
        return out;
    }

    if ( out < 0 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
    return out;
}
2019-01-21 02:58
by Kevin Ng


0

Use this method:

public int ConvertStringToInt(String number)
{
 int num = 0;
 try
 {
   int newNumber = Integer.ParseInt(number);
   num = newNumber;
 }
 catch(Exception ex)
 {
   num = 0;
   Log.i("Console",ex.toString);
 }
   return num;
}
2019-02-18 09:23
by mohamad sheikhi


-1

Try this code with different inputs of String.

        String a="10";  
        String a="10ssda";  
        String a=null; 
        String a="12102";
        if(null!=a){
        try{
         int x= Integer.ParseInt(a.trim()); 
         Integer y= Integer.valueOf(a.trim());
        //  It will throw a NumberFormatException in case of invalid string like ("10ssda" or "123 212") so, put this code into try catch
        }catch(NumberFormatException ex){
          // ex.getMessage();
        }
        }
2018-09-07 09:59
by Ram Chhabra


-1

Some of the ways to convert String into Int are as followings.

1. Integer.parseInt()

String test = "4568";
int new =Integer.parseInt(test);

2. Integer.valueOf()

String test = "4568";
int new =Integer.parseInt(test);

2019-02-06 20:13
by ishant kulshreshtha


-4

Alternatively, you can use Integer.valueOf(). It will return an Integer object.

String numberStringFormat = "10";
Integer resultIntFormat = Integer.valueOf(numberStringFormat);
LOG.info("result:"+result);

Output:

10

2017-04-28 16:59
by KIBOU Hassan
Duplicate answer - Rahul Sharma 2017-04-28 17:27
Ads