Write a Java program to validate PAN No., PAN card number always comes in a specific format like “BJYPP3081R”, Let’s write a Java program to validate the pancard number using regex.
Rules to validate PANCard Number
- There must be ten characters.
- The first five letters must be alphabets followed by a four-digit number and ends with an alphabet
- All alphabets should be in a capital case.
Sample Input and Output to validate PAN No.
- Input consists of a string, which corresponds to the PAN number.
- Output consists of a string – “Valid” or “Invalid”.
Refer sample output for formatting specifications
Sample Input 1:
AHDGS5896I
Sample Output 1:
Valid
Sample Input 2:
OLE124F
Sample Output 2:
Invalid
Write a Java program to validate PAN No
Following are the steps to validate PAN(Permanent Account Number) without regex:
- Input number in string format.
- Convert it into a character array using the toChar() method and pass it to validatePanNo().
- Inside the method, iterate over the character array and check for the following condition
- First, check the length should be less than 10.
- The first five characters should be capital letters.
- The next four should be a number.
- The last digit should be a capital letter.
- At last, if all the above condition is true then return “Valid”.
package com.date; import java.util.Scanner; public class PanNumberValidation { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String pan = scanner.next(); char c[] = pan.toCharArray(); System.out.println(validatePanNo(c)); } private static String validatePanNo(char[] c) { if(c.length!=10){ return "Invalid"; } for(int i =0;i<10;i++){ if((i >= 0 && i<=4) && (c[i] < 'A' || c[i] > 'Z')){ return "Invalid"; } else if((i > 4 && i <=8) && (c[i] < 48 || c[i] > 57)){ return "Invalid"; } else if(i==9 && (c[i] < 'A' || c[i] > 'Z')){ return "Invalid"; } } return "Valid"; } }
Output
Java program to validate PAN No using regex.
Following are the steps to validate PAN(Permanent Account Number) no.:
- Input a String.
- Pass the string to the getValues() method.
- Inside the method, create a regex pattern for PAN no as shown below.Â
regex_pattern = "[A-Z]{5}[0-9]{4}[A-Z]{1}";
-
- [A-Z]{5} – It tells us that the first five should be capital letters.
- [0-9]{4} – Next we should have 4 digits from 0-9.
- [A-Z]{1} – At last, there should be a capital letter.
- If the string matches with the pattern then print Valid else print Invalid.
package com.demo; import java.util.*; public class Main { public static void main(String[] args) { System.out.println("Enter PAN No. :"); Scanner sc = new Scanner(System.in); String s1 = sc.next(); getvalues(s1); } public static void getvalues(String s1) { if (s1.matches("[A-Z]{5}[0-9]{4}[A-Z]{1}")) { System.out.println("Valid"); } else System.out.println("Invalid"); } }
Output
Thus, in this way, we validate PAN(Permanent Account Number) with and without a regex pattern in Java.