Java Program to check if a string is numeric
What are Strings?
A string is a sequence of characters. In Java, strings are used to represent text. You can use strings to store messages, names, and other kinds of text data.
Strings are usually represented as a series of characters enclosed in quotation marks. For example, in Java, you can create a string like this:
String s = “Hello World”;
In this Article, we will write a program to check if a string is numeric.
Strings:
We can use the various methods of the String class to manipulate strings.
For example, you can use the length() method to get the length of a string, the substring() method to get a substring of a string, and the toUpperCase() method to convert a string to uppercase. You can also use the + operator or the concat() method to concatenate two strings.
What is Numeric Strings?
In Java, a string is a sequence of characters. It is not inherently a numeric data type, and cannot be treated as such unless it is specifically converted to a numeric type (such as an int, float, or double).
However, a string may contain numeric characters and still be considered a “numeric string.” For example, the string “12345” is a numeric string because it contains only numeric characters.
To check if a string is numeric in Java, you can use the isDigit() method of the Character class, or you can use the tryParse() method of the Integer, Float, or Double classes.
Program to check if a string is numeric using Isdigit() :
import java.util.*; public class Main{ public static void main(String[] args){ String string1 = "12345"; String string2 = "12345abc"; String string3 = "abcdef"; for (int i = 0; i < string1.length(); i++) { if (!Character.isDigit(string1.charAt(i))) { System.out.println(string1 + " is not a numeric string."); break; } } System.out.println(string1 + " is a numeric string."); for (int i = 0; i < string2.length(); i++) { if (!Character.isDigit(string2.charAt(i))) { System.out.println(string2 + " is not a numeric string."); break; } } for (int i = 0; i < string3.length(); i++) { if (!Character.isDigit(string3.charAt(i))) { System.out.println(string3 + " is not a numeric string."); break; } } } }
Output: 12345 is a numeric string. 12345abc is not a numeric string. abcdef is not a numeric string.
This program will print whether a string is numeric or not using the isdigit() function. If the strings contains only numeric substrings then it is known as numeric substring.
We can test every character of a substring using charAt() method and check whether a character is a integer or not.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment