Java – How to check if a String is an Integer ?

In this article, we will discuss how to check if a String is an Integer or not using different String literals

Check String is an Integer :

Integer.parseInt(str) method converts the given String into an Integer

  • Returns the number, if it contains only numbers/digits
  • Throws NumberFormatException, if it contains alphabets/letters

CheckStringIsInteger.java

package in.bench.resources.string.operation;

public class CheckStringIsInteger {

	public static void main(String[] args) {

		// string literal
		String str1 = "12345";
		String str2 = "a1b2c3";


		// invoke method to check String is integer
		checkInteger(str1);
		checkInteger(str2);
	}


	/**
	 * This method verifies whether the input String is Integer or not ?
	 * - Prints the number if it is an integer
	 * - Prints the message if it is not an integer
	 * @param str
	 */
	public static void checkInteger(String str) {

		try {

			// check String is an Integer
			int number = Integer.parseInt(str);


			// print to console
			System.out.println("The number in String format is :- " + number);

		} catch(NumberFormatException nfex) {

			// print to console
			System.out.print("\nThe input String (" + str + ") contains alphabets");
		}
	}
}

Output :

The number in String format is :- 12345

The input String (a1b2c3) contains alphabets

Related Articles :

References:

Happy Coding !!
Happy Learning !!

Java 8 - How to Reverse a String in place ?
Java – How to remove first and last character from a String ?