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

6,534,108

Solution 1

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 you can 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)

Solution 2

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.

Solution 3

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.

Solution 4

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;
}

Solution 5

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:
6,534,108
Unknown user
Author by

Unknown user

Updated on March 29, 2022

Comments

  • Unknown user
    Unknown user about 2 years

    How can I convert a String to an int?

    "1234"  →  1234
    
    • Pavel Molchanov
      Pavel Molchanov almost 6 years
      By the way, be aware that if the string is null, the call: int i = Integer.parseInt(null); throws NumberFormatException, not NullPointerException.
    • Michael Kay
      Michael Kay almost 5 years
      I'm a little surprised that this question should be so highly rated when an important part of the specification is missing: what should happen if the string DOESN'T contain only digits? For example, many of the answers will happily parse "-1" and return -1, but we don't know if that's acceptable.
    • yerlilbilgin
      yerlilbilgin about 2 years
      The question needs to clarify the radix. Is it 10, 16, 8 ? what ? Maybe base 7
  • hertzsprung
    hertzsprung almost 11 years
    For the differences between the two methods, see this question
  • Admin
    Admin over 9 years
    This will cause -42 to be parsed as 42.
  • yohm
    yohm over 9 years
    What if the input is greater than 2^32? What if the input contains non-numeric characters?
  • Paul Verest
    Paul Verest over 9 years
    valueOf method is just return valueOf(parseInt(string));
  • Dawood ibn Kareem
    Dawood ibn Kareem over 8 years
    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.
  • Billz
    Billz over 8 years
    @yohm those are special case; you can handle with long and some regex; however, by then you can use parseInt.
  • Holger
    Holger about 8 years
    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…
  • wnoise
    wnoise about 8 years
    You rarely want 0 to be used when an invalid number is parsed.
  • SusanW
    SusanW almost 8 years
    -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.
  • Rahul Sharma
    Rahul Sharma about 7 years
    Duplicate answer.
  • etherous
    etherous almost 7 years
    @Ryboflavin No, it doesn't. One of those is a well-defined language semantic, and the other is an exception
  • Steve Smith
    Steve Smith almost 7 years
    This is exactly the same as the select answer.
  • Dawood ibn Kareem
    Dawood ibn Kareem over 6 years
    There is no value to the site, in repeating an answer that someone else posted FIVE YEARS before you.
  • Dorian Gray
    Dorian Gray over 6 years
    There is no need to reinvent the wheel, just use Integer.parseInt.
  • Anup Gupta
    Anup Gupta over 6 years
    @TobiasWeimer yes, we can do but this is without using library
  • Anup Gupta
    Anup Gupta over 6 years
    @TobiasWeimer, some people need this how to do without using Library.
  • Dorian Gray
    Dorian Gray over 6 years
    No, no one needs it because it is a function inside the JDK, not some third party plugin.
  • Allison
    Allison over 6 years
    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.
  • 463035818_is_not_a_number
    463035818_is_not_a_number almost 6 years
    how can I parse "26263Hello" ? I want to extract 26263 in that case
  • Mark Stewart
    Mark Stewart almost 6 years
    @user463035818 - See docs.oracle.com/javase/8/docs/api/java/util/regex/… - 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.
  • Sundararaj Govindasamy
    Sundararaj Govindasamy over 5 years
    NumberUtils handles null and empty scenarios as well.
  • Nathan Adams
    Nathan Adams about 5 years
    -1 because what if I want to parse a base 31 int? Integer.parseInt(str, 31) is a one liner to do that. Slightly facetious comment, but serious point underneath. Never re-invent wheels when someone else has already put the work in
  • Wai Ha Lee
    Wai Ha Lee almost 5 years
    Both examples are the same
  • Peter Mortensen
    Peter Mortensen over 4 years
    Some explanation would be in order.
  • Peter Mortensen
    Peter Mortensen over 4 years
    Why is s.trim() necessary?
  • Peter Mortensen
    Peter Mortensen over 4 years
    Isn't this covered in previous answers?
  • Peter Mortensen
    Peter Mortensen over 4 years
    It is not the only duplicate answer. We are now at 93 answers (includes deleted) for this simple question.
  • Peter Mortensen
    Peter Mortensen over 4 years
    This is already covered in the accepted answer (posted about 5 years prior).
  • Peter Mortensen
    Peter Mortensen over 4 years
    This is already covered in the accepted answer (posted about 5 years prior).
  • Kevin Ng
    Kevin Ng over 4 years
    Thank you, Peter, for making an edit for me. It looked pretty good. I was wondering if you can help me making a project based almost on this code that I started to become better. This is the link to the project github.com/kevinhng86/Java-host.fai.lib.faiNumber .
  • Kevin Ng
    Kevin Ng over 4 years
    Also, to clarify. The reason why having the power array method ran faster is that Java cached the result for this type of test code. I tested, in a real-life situation, using bit shift will work way faster.
  • skomisa
    skomisa about 4 years
    How does this add anything? There are several older answers that have already provided these approaches. Please read existing answers before posting.
  • Peter Mortensen
    Peter Mortensen over 3 years
    Why is an empty if necessary? Why not just Integer.parseInt(myString), out myInt?
  • Peter Mortensen
    Peter Mortensen over 3 years
    Re "You need to handle NumberFormatException for the string value issue": How? By avoiding it happening altogether by one of these three methods? Can you make it more clear (without "Update: ", "Edit: " or similar)?
  • Peter Mortensen
    Peter Mortensen over 3 years
    What are the magic numbers 48 and 57? Can't (named) constants be used?
  • Sachini Witharana
    Sachini Witharana over 3 years
    @PeterMortensen without the if condition we cannot out myInt
  • Basilevs
    Basilevs over 3 years
  • user1644002
    user1644002 over 2 years
    He is showing the efficiency of one is greater than the efficiency of the other.
  • Peter Mortensen
    Peter Mortensen over 2 years
    How does this not repeat a previous answer, more than 9 years later? For instance, the accepted answer.
  • Peter Mortensen
    Peter Mortensen over 2 years
    That doesn't sound plausible. Can you provide a reference? Please respond by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).
  • Stephen C
    Stephen C over 2 years
    @user1644002 - Well if he (and you) think that, then he is (probably) incorrect. The JIT compiler should inline the valueOf -> parseInt call making the two versions equally efficient.
  • Stephen C
    Stephen C over 2 years
    This is not valid Java code. I'm not even sure what it is supposed to mean ... in any programming language.
  • Ali Mamedov
    Ali Mamedov over 2 years
    It works perfectly. Thank you!
  • OneCricketeer
    OneCricketeer about 2 years
    If you aren't using JavaFX GUI framework, shouldn't use its imports
  • OneCricketeer
    OneCricketeer about 2 years
    This is only two ways. Introduction of an optional doesn't change that you're using parseInt
  • Yann Vo
    Yann Vo about 2 years
    You can also specify your own default value with the overloaded method NumberUtils.toInt(String, int);