Mask Phone Numbers example give how to mask phone numbers using replaceAll in Java. It also shows how to mask starting of few digits with the # (Hash) of the phone numbers.
here we are assuming that we want to display the last 4 digits out of 10.The rest of the number need to be displayed as an #.
here first we find the length of phone number.after that we use substring method to find mask number.now we find number of digit to unmask from substring mathod.after that we use “[^0-9]” to replace all non-digit characters.now we add mask and unmask number to get response.
public class MaskPhoneNumber {
public static void main(String[] args) {
String phoneNumber = "8888888888";
// find length of phone number
int phoneNoLen = phoneNumber.length();
String response = "";
String unMaskedNumber = "";
String maskNumber = "";
// find mask number
maskNumber = phoneNumber.substring(phoneNoLen - 4, phoneNoLen);
// find total unmask number
unMaskedNumber = phoneNumber.substring(0, phoneNoLen - 4);
// replace total unmask number from #(Hash)
unMaskedNumber = unMaskedNumber.replaceAll("[0-9]", "#");
// add mask and unmask number
response = unMaskedNumber + maskNumber;
System.out.println("phone number:- " + response);
}
}
Output :-
phone number:- ######8888