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 :
- Java – Remove duplicate characters from String in Java
- Java – How to UPPERCASE every duplicate character/occurrences in a String in Java
- Java – How to check whether 2 strings are Anagrams in Java ?
- Java – How to remove white-spaces in a String ?
- Java – How to swap 2 Strings without using Third variable ?
- Java – Count and print number of Vowels and Consonants in a String
- Java – Remove input-ted Character from a given String
- Java – How to check whether given String contains only Alphabets or Letters ?
- Java – How to check whether given String contains only Digits ?
- Java – How to check whether given String contains Alpha-numeric characters only ?
- Java – How to check if a String is an Integer ?
- Java – How to remove special characters from String ?
- Java – How to remove last comma (,) from String ?
- Java – How to count length of last word in a String ?
- Java – How to find first and last character in a String ?
- Java – How to remove first and last character from a String ?
References:
Happy Coding !!
Happy Learning !!