Exercise:
Write a Java Program to check if a string is numeric.
1.check using if-statement
Click Here to View the Solution!
public class IsNumeric {
public static void main(String[] args) {
String string = "1786.3873";
boolean numeric = true;
try {
Double num = Double.parseDouble(string);
} catch (NumberFormatException e) {
numeric = false;
}
if(numeric)
System.out.println(string + " is a numeric value");
else
System.out.println(string + " is not a numeric value");
}
}
Click Here to View the Output!
1786.3873 is a numeric value
Click Here to View the Explanation!
- This program deals with finding out if the contents of a given string are of numeric value or not.
- Here a string having a value
1786.3873
is stored in aString
type variable namedstring
. - Also a ‘boolean’ type variable ‘numeric’ is initialized having ‘true’ as its value primarily.
- The
try and catch
segment deals with verifying whether the string possesses a numeric value or not. - For this purpose, first the string is passed to
parseDouble()
method to convert the string to its double value equivalent. - If the string is not a numeric value, then an exception by the name of
NumberFormatException
is thrown and the value of ‘numeric’ is changes to ‘false’. - If the value of ‘numeric’ is a number, then an output is displayed on the console.
2.Check using Regular expression
Click Here to View the Solution!
public class Numeric {
public static void main(String[] args) {
String string = "9.876ty";
boolean numeric = true;
numeric = string.matches("-?\\d+(\\.\\d+)?");
if(numeric)
System.out.println(string + " is a numeric value");
else
System.out.println(string + " is not a numeric value");
}
}
Click Here to View the Output!
9.876ty is not a numeric value
Click Here to View the Explanation!
- This program deals with finding out if the contents of a given string are of numeric value or not by employing regular expressions.
- Unlike the previous example,
try-catch
method has not been employed in this example. - The
matches()
function is called upon the givenstring
having a value of9.876ty
. - A regular expression is passed within
mathes()
, that check different parts of the string in order to verify if it is numeric or not. - The first figment of regular expression i.e. ‘-?’ checks whether there exists a negative sign or not.
- Whereas the second figment ‘\\d+’ whether there exists a number or not. (at-least one number should exist)
- The next segment (‘\\. \\d+’) has two parts further: ‘\\.’ Verifies whether there exists a decimal point.
- If so is the case, then the next part ‘\\d+’ makes sure that there must be one number at least. (More numbers can follow too!).
- The output depicts that
9.876ty is not a numrical value
.