4 Ways to Check if String is Integer in Java

There are situations when we need to check if a string is an integer. I will be telling you some of the ways to perform this operation in this article. Let us go through all the methods one after another along with their explanation.

1. Using parseInt method

The parseInt method comes inside the Integer class which checks whether a string can be converted to a number. If it is possible then the method returns the converted integer value otherwise it throws a NumberFormatException error.

import java.util.Scanner;

public class checkstrtoint {
   public static boolean numcheck(String ms) {
      try {
        Integer.parseInt(ms);
      }catch(Exception e){
        return false;
      }
 
      return true;
   }
   public static void main(String[] args) {
      Scanner sc=new Scanner(System.in);
      System.out.println("Please Enter the string as an input: ");
      String mystring=sc.next();

      if(numcheck(mystring)==true) {
         System.out.println("Yes given string is an integer");
      }else {
         System.out.println("No given string is not an integer");
      } 
  }

}

Output:

Please Enter the string as an input: 
12p3
No given string is not an integer

Explanation:

Let us see the explanation of the code in an elaborative manner. Firstly we are creating an object of the Scanner class which helps us to take input. Now we are taking the input from the user and calling the numcheck() method. Inside the numcheck method try and catch block is used to check whether we are able to convert the input string to an integer or not. If it’s not possible then the catch block returns false followed by printing “No given string is not an integer”. If the given string can be converted successfully into an integer then we simply print “Yes given string is an integer”.

2. Using Regular Expressions (regex)

We can use java.util.regex to find certain patterns in the given string. Therefore it can also be used to check whether the given string consists of only numerical digits or not.

import java.util.*;
 
public class checkstrtoint {
   public static void main(String[] args) {
     Scanner sc=new Scanner(System.in);
 
     System.out.println("Please Enter the string as an input: ");
     String mystring=sc.next();
     String regex = "[0-9]+";
     if(mystring.matches(regex)==true) {
    	 System.out.println(mystring + " is a valid integer number");
     }else {
        System.out.println(mystring + " is not a valid integer number");
     }
   }
}

Output:

Please Enter the string as an input:
1231456416541214
1231456416541214 is a valid integer number

Explanation:

Let us see the explanation of the code in an elaborative manner. Firstly we are creating an object of the Scanner class which helps us to take input. Now we are taking the input from the user and then using the try & catch block to check whether a given string is an integer or not. Inside the try block, a regex function matches() is used if it executes successfully then the instructions on the next line are printed. Otherwise, catch block is executed and we print that the given string is not a valid integer number.

3. Using BigInteger Method

import java.math.BigInteger;
import java.util.*;

public class checkstrtoint {
   public static void main(String[] args) {
     Scanner sc=new Scanner(System.in);

     System.out.println("Please Enter the string as an input: ");
     String mystring=sc.next();

     try {
       new BigInteger(mystring);
       System.out.println ( mystring + " is a valid integer number" );
     }catch ( NumberFormatException e ) {
       System.out.println ( mystring + " is not a valid integer number" );
     }
  }
}

Output:

Please Enter the string as an input: 
123145641654121411111
123145641654121411111 is a valid integer number

Explanation:

Let us see the explanation of the code in an elaborative manner. Firstly we are creating an object of the Scanner class which helps us to take input. Now we are taking the input from the user and then using the try & catch block to check whether a given string is an integer or not. Inside the try block, we will use the BigInteger constructor for bigger numbers. If it is executed successfully then we can simply print the given number as an integer. Otherwise, the code written in the catch block is executed through which we can print that the given number is not an integer.

4. Using for Loop

import java.math.BigInteger;
import java.util.*;

public class checkstrtoint {
    public static void main(String[] args) {
     Scanner sc=new Scanner(System.in);
     System.out.println("Please Enter the string as an input: ");
     String mystring=sc.next();

     int wrong=0;
     for(int i=0;i<mystring.length();i++) {
        char tp=mystring.charAt(i);
        int tempval=tp-'0';
        if(tempval>=0 & tempval<=9) { 
        
        }else {
         wrong=1;
         break;
        }
     }
     if(wrong==0) {
        System.out.println(mystring + " is a valid integer number" );
     }else {
        System.out.println(mystring + " is not a valid integer number");
     }
   }
}

Output:

Please Enter the string as an input: 
51536a
51536a is not a valid integer number

Explanation:

Let us see the explanation of the code in an elaborative manner. Firstly we are creating an object of the Scanner class which helps us to take input. Now we are taking the input from the user and then checking each character whether it’s a digit or not. Here an integer variable wrong is created which is incremented if we encounter any character that isn’t a digit. At last, the if & else condition is used to check whether the value of wrong is 0 or more. If it’s 0 then the given string is a valid integer number. Otherwise, the given string isn’t a valid integer number.

Conclusion

Through this blog, we learned different methods to check whether an input string is an integer or not. Majorly build-in methods along with the simple method of using for loop are discussed above. There were some more methods in the Apache Comms library that provides the same functionality. You can explore this third party library if you want to learn more. I hope you were able to grasp the concepts clearly, feel free to comment below if you are facing any doubts. I will be happy to resolve all the queries.

Leave a Comment

Your email address will not be published. Required fields are marked *