Replace all letters of a string minus the first and the last in Java

In one line regex you can do:

String str = "stackoverflow";
String repl = str.replaceAll("\\B\\w\\B", "*");
//=> s***********w

RegEx Demo

\B is zero-width assertion that matches positions where \b doesn't match. That means it matches every letter except first and last.


char[] charArr = username.toCharArray();
for (int i=1;i<charArr.length - 1;i++) {
  charArr[i] = 'x';

}
username = new String(charArr);

If the string also can contain punctuation try:

str = str.replaceAll("(?!^).(?!$)","*");

The lookarounds assure to not being at start or end (regex101 demo).