- To check if first character of a string is a number or not in java we can check in multiple ways.
- By using Character.isDigit() method by passing character of string using for loop or substring method.
- Other way is to check str.substring(0, 1).matches("[0-9]").
- Lets see an example program in java to check first character of a string is digit or character.
Program #1: Java example program to check the each character of string is number or not character is a letter or number in Java without using regexes?
- package StringInterviewprograms;
- /**
- * Check whether the given character is a number /digit or not by using java character isdigit
- *method
- * @author www.instanceofjava.com
- */
- public class CheckEachCharacterNumberOrNot {
- public static void main(String[] args) {
- String str = "instanceofjava37";
- //Check whether the given character is a number /digit or not ?
- for(int i=0; i<str.length();i++)
- {
- Boolean flag = Character.isDigit(str.charAt(i));
- if(flag){
- System.out.println("'"+str.charAt(i)+"' is a number");
- }
- else{
- System.out.println("'"+str.charAt(i)+"' is not a number");
- }
- }
- }
- }
Output:
- 'i' is not a number
- 'n' is not a number
- 's' is not a number
- 't' is not a number
- 'a' is not a number
- 'n' is not a number
- 'c' is not a number
- 'e' is not a number
- 'o' is not a number
- 'f' is not a number
- 'j' is not a number
- 'a' is not a number
- 'v' is not a number
- 'a' is not a number
- '3' is a number
- '7' is a number
Program #2: Java example program to check the First character of string is number or not by using regex.
- package StringInterviewprograms;
- /**
- * Check whether the given character is a number /digit or not
- * @author www.instanceofjava.com
- */
- public class CheckFirstCharacterNumberOrNot {
- public static void main(String[] args) {
- String str = "instanceofjava37";
- Boolean flag1 = str.substring(0, 1).matches("[0-9]");
- if(flag1){
- System.out.println("First Character is a number..!");
- }
- else{
- System.out.println("First character is not a number..!");
- }
- }
- }
Output:
- First character is not a number..!
Program #3: Java example program to check the First character of string is number or not using eclipse IDE.
No comments