How do I convert a String to an int in Java?
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 ofjava.lang.Integer
-
parseInt
returns primitiveint
.
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.
Unknown user
Updated on March 29, 2022Comments
-
Unknown user about 2 years
How can I convert a
String
to anint
?"1234" → 1234
-
Pavel Molchanov almost 6 yearsBy the way, be aware that if the string is null, the call: int i = Integer.parseInt(null); throws NumberFormatException, not NullPointerException.
-
Michael Kay almost 5 yearsI'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 about 2 yearsThe question needs to clarify the radix. Is it 10, 16, 8 ? what ? Maybe base 7
-
-
hertzsprung almost 11 yearsFor the differences between the two methods, see this question
-
Admin over 9 yearsThis will cause
-42
to be parsed as42
. -
yohm over 9 yearsWhat if the input is greater than 2^32? What if the input contains non-numeric characters?
-
Paul Verest over 9 years
valueOf
method is justreturn valueOf(parseInt(string));
-
Dawood ibn Kareem over 8 yearsOne 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 over 8 years@yohm those are special case; you can handle with long and some regex; however, by then you can use parseInt.
-
Holger about 8 yearsIt’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 of48
and never have to bother with its actual numeric value. Third, the entire detour withdouble
values makes no sense at all as you are dividing by ten, just to multiply with ten afterwards. The result simply issemilastdigit * 10 + lastdigit
as learnt in elementary school, when the decimal system was introduced… -
wnoise about 8 yearsYou rarely want 0 to be used when an invalid number is parsed.
-
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 about 7 yearsDuplicate answer.
-
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 almost 7 yearsThis is exactly the same as the select answer.
-
Dawood ibn Kareem over 6 yearsThere is no value to the site, in repeating an answer that someone else posted FIVE YEARS before you.
-
Dorian Gray over 6 yearsThere is no need to reinvent the wheel, just use
Integer.parseInt
. -
Anup Gupta over 6 years@TobiasWeimer yes, we can do but this is without using library
-
Anup Gupta over 6 years@TobiasWeimer, some people need this how to do without using Library.
-
Dorian Gray over 6 yearsNo, no one needs it because it is a function inside the JDK, not some third party plugin.
-
Allison over 6 yearsIn 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 almost 6 yearshow can I parse "26263Hello" ? I want to extract 26263 in that case
-
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 theMatcher
class in that package. -
Sundararaj Govindasamy over 5 yearsNumberUtils handles null and empty scenarios as well.
-
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 almost 5 yearsBoth examples are the same
-
Peter Mortensen over 4 yearsSome explanation would be in order.
-
Peter Mortensen over 4 yearsWhy is
s.trim()
necessary? -
Peter Mortensen over 4 yearsIsn't this covered in previous answers?
-
Peter Mortensen over 4 yearsIt is not the only duplicate answer. We are now at 93 answers (includes deleted) for this simple question.
-
Peter Mortensen over 4 yearsThis is already covered in the accepted answer (posted about 5 years prior).
-
Peter Mortensen over 4 yearsThis is already covered in the accepted answer (posted about 5 years prior).
-
Kevin Ng over 4 yearsThank 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 over 4 yearsAlso, 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 about 4 yearsHow does this add anything? There are several older answers that have already provided these approaches. Please read existing answers before posting.
-
Peter Mortensen over 3 yearsWhy is an empty
if
necessary? Why not justInteger.parseInt(myString), out myInt
? -
Peter Mortensen over 3 yearsRe "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 over 3 yearsWhat are the magic numbers 48 and 57? Can't (named) constants be used?
-
Sachini Witharana over 3 years@PeterMortensen without the if condition we cannot out myInt
-
Basilevs over 3 years
-
user1644002 over 2 yearsHe is showing the efficiency of one is greater than the efficiency of the other.
-
Peter Mortensen over 2 yearsHow does this not repeat a previous answer, more than 9 years later? For instance, the accepted answer.
-
Peter Mortensen over 2 yearsThat 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 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 over 2 yearsThis is not valid Java code. I'm not even sure what it is supposed to mean ... in any programming language.
-
Ali Mamedov over 2 yearsIt works perfectly. Thank you!
-
OneCricketeer about 2 yearsIf you aren't using JavaFX GUI framework, shouldn't use its imports
-
OneCricketeer about 2 yearsThis is only two ways. Introduction of an optional doesn't change that you're using parseInt
-
Yann Vo about 2 yearsYou can also specify your own default value with the overloaded method NumberUtils.toInt(String, int);