eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

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 – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

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.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

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 – LSS – NPI (cat=Security/Spring Security)
announcement - icon

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)
1 Comment
Oldest
Newest
Inline Feedbacks
View all comments