Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Introduction

Privacy and data security are important elements of software development. Masking sensitive details such as the user’s email address and phone number is usually one procedure used to safeguard user information and prevent its disclosure.

In this tutorial, we’ll investigate how to mask email addresses and phone numbers in Java.

2. Masking Email Addresses

2.1. Using String Manipulation

String manipulation is one of the ways to hide an email by editing the characters and replacing a few with asterisks. Here’s a simple Java code snippet demonstrating this approach:

String email = "[email protected]";
String expectedMaskedEmail = "te**************@example.com";

@Test
public void givenEmailAddress_whenUsingStringManipulation_thenMaskEmail() {
    int atIndex = email.indexOf('@');
    String repeatedString = IntStream.range(0, atIndex - 2).mapToObj(i -> "*").collect(Collectors.joining());
    String maskedPart = email.substring(0, atIndex - repeatedString.length()) + repeatedString;
    String maskedEmail = maskedPart + email.substring(atIndex);

    assertEquals(expectedMaskedEmail, maskedEmail);
}

In the given example, we first find the index of the “@” character in the email address. Then, we generate a string of asterisks with a length equal to atIndex-2 using Java’s Stream API and string operations. Note that we subtract 2 digits from the atIndex to make the first two digits of the email.

The maskedPart of the email is generated by combining the characters before the “@” symbol with the generated string of asterisks in the context of the provided Java code.

The email address is then obtained by concatenating the maskedPart and the generated asterisks. Finally, we use the assertEquals() method to verify that the maskedEmail is the same as the expectedMaskedEmail.

2.2. Using Regular Expressions

Another method is to implement regular expressions to conceal the email address. Here’s an example:

@Test
public void givenEmailAddress_whenUsingRegex_thenMaskEmail() {
    int atIndex = email.indexOf('@');
    String regex = "(.{2})(.*)(@.*)";
    String repeatedAsterisks = "*".repeat(atIndex - 2);
    String maskedEmail = email.replaceAll(regex, "$1" + repeatedAsterisks + "$3");

    assertEquals(expectedMaskedEmail, maskedEmail);
}

In the above test method, we first determine the index of the “@” symbol in the email using the indexOf() method. Then, we use the regular expression regex “(.{2})(.*)(@.*)” to capture three groups: the first two characters, the characters between them and the “@” symbol, and the characters following the “@“.

Subsequently, the variable repeatedAsterisks is assigned a string of asterisks with a length corresponding to atIndex -2. Finally, the replaceAll() method applies the regex pattern, replacing the middle part of the email with the generated asterisks.

3. Masking Phone Numbers

3.1. Using String Manipulation

We can also mask phone numbers by performing some character manipulations. Here’s an example:

String phoneNumber = "+1234567890";
String expectedMaskedPhoneNumber = "+******7890";

@Test
public void givenPhoneNumber_whenUsingStringManipulation_thenMaskPhone() {
    String maskedPhoneNumber = phoneNumber.replaceAll("\\d(?=\\d{4})", "*");

    assertEquals(expectedMaskedPhoneNumber, maskedPhoneNumber);
}

Here, we pass the regular expression “\\d(?=\\d{4})” to the replaceAll() method, aiming to identify and replace all numeric digits that are followed by four more digits with asterisks.

3.2. Using Regular Expressions

Similarly to the method used for masking email addresses, regular expressions can be implemented to hide the phone numbers properly. Here’s a Java code snippet demonstrating this method:

@Test
public void givenPhoneNumber_whenUsingRegex_thenMaskPhone() {
    int lastDigitsIndex = phoneNumber.length() - 5;
    String regex = "(\\+)(\\d+)(\\d{4})";
    String repeatedAsterisks = "*".repeat(Math.max(0, lastDigitsIndex));
    String maskedPhoneNumber = phoneNumber.replaceAll(regex, "$1" + repeatedAsterisks + "$3");

    assertEquals(expectedMaskedPhoneNumber, maskedPhoneNumber);
}

In the above code snippet, we define a regular expression regex “(\\+)(\\d+)(\\d{4})” that captures three groups: the plus sign, the leading digits, and the last four digits.

Subsequently, we generate a string repeatedAsterisks of repeated asterisks based on the calculated lastDigitsIndex. Then,  we use the replaceAll() method to apply the regex pattern, replacing the middle digits with asterisks.

4. Conclusion

In conclusion, the masking of sensitive information is critical for protecting user privacy and adhering to data security regulations. Hence, we see in this tutorial how to utilize mechanisms such as string manipulation and regular expressions to mask email addresses and phone numbers.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1 Comment
Oldest
Newest