if I want to convert a string into an int in java do you know if there is a way for me to detect overflow? by that I mean the string literal actually represents a value which is larger than MAX_INT?
java doc didn't mention it.. it just says that if the string can not be parsed as an integer, it will through FormatException didn't mention a word about overflow..
If I want to convert a string into an int in java do you know if there is a way for me to detect overflow?
Yes. Catching parse exceptions would be the correct approach, but the difficulty here is that Integer.parseInt(String s)
throws a NumberFormatException
for any parse error, including overflow. You can verify by looking at the Java source code in the JDK's src.zip
file. Luckily, there exists a constructor BigInteger(String s)
that will throw identical parse exceptions, except for range limitation ones, because BigInteger
s have no bounds. We can use this knowledge to trap the overflow case:
/**
* Provides the same functionality as Integer.parseInt(String s), but throws
* a custom exception for out-of-range inputs.
*/
int parseIntWithOverflow(String s) throws Exception {
int result = 0;
try {
result = Integer.parseInt(s);
} catch (Exception e) {
try {
new BigInteger(s);
} catch (Exception e1) {
throw e; // re-throw, this was a formatting problem
}
// We're here iff s represents a valid integer that's outside
// of java.lang.Integer range. Consider using custom exception type.
throw new NumberFormatException("Input is outside of Integer range!");
}
// the input parsed no problem
return result;
}
If you really need to customize this for only inputs exceeding Integer.MAX_VALUE, you can do that just before throwing the custom exception, by using @Sergej's suggestion. If above is overkill and you don't need to isolate the overflow case, just suppress the exception by catching it:
int result = 0;
try {
result = Integer.parseInt(s);
} catch (NumberFormatException e) {
// act accordingly
}
Cast String value to Long and compare Long value with Integer.Max_value
String bigStrVal="3147483647";
Long val=Long.parseLong(bigStrVal);
if (val>Integer.MAX_VALUE){
System.out.println("String value > Integer.Max_Value");
}else
System.out.println("String value < Integer.Max_Value");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With