I have a pinNumber value. How to mask it (ie) say if my pinNumber is 1234 and mask it with four asteriks symbol instead of showing the numbers. This masked value will be shown in a webpage using a jsp.
7 Answers
At some point in your code, you will convert the number to a string for display. At this point, you can simply call String's replaceAll method to replace all the characters from 0-9 with * character :
s.replaceAll("[0-9]", "*")
well - this is how you do it directly in Java. In JSP it is taken care of for you, as other posters show, if you select 'password' type on your input.

- 2,196
- 1
- 12
- 15
<input type="PASSWORD" name="password">
If you are going to display a password on a label, just display 5 or 6 asterisk characters as you do not want to give them clues by making the length of that label with the length of the password.

- 18,272
- 11
- 52
- 74
You create form like that
<form action="something" method="post">
pinNumber:<input type="password" name="pass"/>
<input type="submit" value="OK"/>
</form>
then it will change the into *

- 494
- 1
- 4
- 11
This code might help you.
class Password {
final String password; // the string to mask
Password(String password) { this.password = password; } // needs null protection
// allow this to be equal to any string
// reconsider this approach if adding it to a map or something?
public boolean equals(Object o) {
return password.equals(o);
}
// we don't need anything special that the string doesnt
public int hashCode() { return password.hashCode(); }
// send stars if anyone asks to see the string - consider sending just
// "******" instead of the length, that way you don't reveal the password's length
// which might be protected information
public String toString() {
StringBuilder sb = new StringBuilder();
for(int i = 0; < password.length(); i++)
sb.append("*");
return sb.toString();
}
}

- 1,115
- 1
- 15
- 44
I use following code in my many application and it works nicely.
public class Test {
public static void main(String[] args) {
String number = "1234";
StringBuffer maskValue = new StringBuffer();
if(number != null && number.length() >0){
for (int i = 0; i < number.length(); i++) {
maskValue.append("*");
}
}
System.out.println("Masked Value of 1234 is "+maskValue);
}
}
Ans - Masked Value of 1234 is ****
Two ways (this will mask all charecters not only numbers) :
private String mask(String value) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < value.length(); sb.append("*"), i++);
return sb.toString();
}
or:
private String mask(String value) {
return value.replaceAll(".", "*");
}
I use the second one

- 199
- 2
- 10
using @Mask annotation.
@Mask(prefixNoMaskLen = 3, maskStr = "*", suffixNoMaskLen = 3) private String mobileNumber;
This will mask the mobile number from 987654321 to 987****321