Determine If a String Is an Integer in Java

Determine if a String is an Integer in Java

The most naive way would be to iterate over the String and make sure all the elements are valid digits for the given radix. This is about as efficient as it could possibly get, since you must look at each element at least once. I suppose we could micro-optimize it based on the radix, but for all intents and purposes this is as good as you can expect to get.

public static boolean isInteger(String s) {
return isInteger(s,10);
}

public static boolean isInteger(String s, int radix) {
if(s.isEmpty()) return false;
for(int i = 0; i < s.length(); i++) {
if(i == 0 && s.charAt(i) == '-') {
if(s.length() == 1) return false;
else continue;
}
if(Character.digit(s.charAt(i),radix) < 0) return false;
}
return true;
}

Alternatively, you can rely on the Java library to have this. It's not exception based, and will catch just about every error condition you can think of. It will be a little more expensive (you have to create a Scanner object, which in a critically-tight loop you don't want to do. But it generally shouldn't be too much more expensive, so for day-to-day operations it should be pretty reliable.

public static boolean isInteger(String s, int radix) {
Scanner sc = new Scanner(s.trim());
if(!sc.hasNextInt(radix)) return false;
// we know it starts with a valid int, now make sure
// there's nothing left!
sc.nextInt(radix);
return !sc.hasNext();
}

If best practices don't matter to you, or you want to troll the guy who does your code reviews, try this on for size:

public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}

How can I check if a value is of type Integer?

If input value can be in numeric form other than integer , check by

if (x == (int)x)
{
// Number is integer
}

If string value is being passed , use Integer.parseInt(string_var).
Please ensure error handling using try catch in case conversion fails.

How to check if a String is numeric in Java

With Apache Commons Lang 3.5 and above: NumberUtils.isCreatable or StringUtils.isNumeric.

With Apache Commons Lang 3.4 and below: NumberUtils.isNumber or StringUtils.isNumeric.

You can also use StringUtils.isNumericSpace which returns true for empty strings and ignores internal spaces in the string. Another way is to use NumberUtils.isParsable which basically checks the number is parsable according to Java. (The linked javadocs contain detailed examples for each method.)

What's the best way to check if a String represents an integer in Java?

If you are not concerned with potential overflow problems this function will perform about 20-30 times faster than using Integer.parseInt().

public static boolean isInteger(String str) {
if (str == null) {
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
i = 1;
}
for (; i < length; i++) {
char c = str.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
return true;
}

How to check if a string is a valid integer?

You can't do if (int i = 0), because assignment returns the assigned value (in this case 0) and if expects an expression that evaluates either to true, or false.

On the other hand, if your goal is to check, whether jTextField.getText() returns a numeric value, that can be parsed to int, you can attempt to do the parsing and if the value is not suitable, NumberFormatException will be raised, to let you know.

try {
op1 = Integer.parseInt(jTextField1.getText());
} catch (NumberFormatException e) {
System.out.println("Wrong number");
op1 = 0;
}

How to determine whether a string contains an integer?

If you want to make sure that it is only an integer and convert it to one, I would use parseInt in a try/catch. However, if you want to check if the string contains a number then you would be better to use the String.matches with Regular Expressions: stringVariable.matches("\\d")

How to check the input is an integer or not in Java?

If you are getting the user input with Scanner, you can do:

if(yourScanner.hasNextInt()) {
yourNumber = yourScanner.nextInt();
}

If you are not, you'll have to convert it to int and catch a NumberFormatException:

try{
yourNumber = Integer.parseInt(yourInput);
}catch (NumberFormatException ex) {
//handle exception here
}

Check if a String is Integer

You can try a regex like:

Code

private boolean isInteger(String str) {
return str.matches("\\-?\\d+");
}

Edit

Thanks @Maloubobola for noting that my first attempt would not parse signed integers.



Related Topics



Leave a reply



Submit