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. Overview

In this quick tutorial, we’ll see how to use Google’s open-source library libphonenumber to validate phone numbers in Java.

2. Maven Dependency

First, we’ll need to add the dependency for this library in our pom.xml:

<dependency>
    <groupId>com.googlecode.libphonenumber</groupId>
    <artifactId>libphonenumber</artifactId>
    <version>8.12.10</version>
</dependency>

The latest version information can be found over on Maven Central.

Now, we’re equipped to use all the functionality this library has to offer.

3. PhoneNumberUtil

The library provides a utility class, PhoneNumberUtil, which provides several methods to play around with phone numbers.

Let’s see a few examples of how we can use its various APIs for validation.

Importantly, in all examples, we’ll be using the singleton object of this class to make method calls:

PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();

3.1. isPossibleNumber

Using PhoneNumberUtil#isPossibleNumber, we can check if a given number is possible for a particular country code or region.

As an example, let’s take the United States, which has a country code of 1. We can check if given phone numbers are possible US numbers in this fashion:

@Test
public void givenPhoneNumber_whenPossible_thenValid() {
    PhoneNumber number = new PhoneNumber();
    number.setCountryCode(1).setNationalNumber(123000L);
    assertFalse(phoneNumberUtil.isPossibleNumber(number));
    assertFalse(phoneNumberUtil.isPossibleNumber("+1 343 253 00000", "US"));
    assertFalse(phoneNumberUtil.isPossibleNumber("(343) 253-00000", "US"));
    assertFalse(phoneNumberUtil.isPossibleNumber("dial p for pizza", "US"));
    assertFalse(phoneNumberUtil.isPossibleNumber("123-000", "US"));
}

Here, we used another variant of this function as well by passing in the region that we’re expecting the number to be dialed from as a String.

3.2. isPossibleNumberForType

The library recognizes different types of phone numbers, such as fixed-line, mobile, toll-free, voicemail, VoIP, pager, and many more.

Its utility method isPossibleNumberForType checks if the given number is possible for a given type in a particular region.

As an example, let’s go for Argentina since it allows for different possible lengths of numbers for different types.

Hence, we can use it to demonstrate the capability of this API:

@Test
public void givenPhoneNumber_whenPossibleForType_thenValid() {
    PhoneNumber number = new PhoneNumber();
    number.setCountryCode(54);

    number.setNationalNumber(123456);
    assertTrue(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE));
    assertFalse(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.TOLL_FREE));

    number.setNationalNumber(12345678901L);
    assertFalse(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE));
    assertTrue(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.MOBILE));
    assertFalse(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.TOLL_FREE));
}

As we can see, the above code validates that Argentina permits 6-digit fixed line numbers and 11-digit mobile numbers.

3.3. isAlphaNumber

This method is used to verify if the given phone number is a valid alphanumeric one, such as 325-CARS:

@Test
public void givenPhoneNumber_whenAlphaNumber_thenValid() {
    assertTrue(phoneNumberUtil.isAlphaNumber("325-CARS"));
    assertTrue(phoneNumberUtil.isAlphaNumber("0800 REPAIR"));
    assertTrue(phoneNumberUtil.isAlphaNumber("1-800-MY-APPLE"));
    assertTrue(phoneNumberUtil.isAlphaNumber("1-800-MY-APPLE.."));
    assertFalse(phoneNumberUtil.isAlphaNumber("+876 1234-1234"));
}

To clarify, a valid alpha number contains at least three digits at the beginning, followed by three or more alphabet letters. The utility method above first strips the given input off any formatting and then checks for this condition.

3.4. isValidNumber

The previous API we discussed quickly checks the phone number on the basis of its length only. On the other hand, isValidNumber does a complete validation using prefix as well as length information:

@Test
public void givenPhoneNumber_whenValid_thenOK() throws Exception {

    PhoneNumber phone = phoneNumberUtil.parse("+911234567890", 
      CountryCodeSource.UNSPECIFIED.name());

    assertTrue(phoneNumberUtil.isValidNumber(phone));
    assertTrue(phoneNumberUtil.isValidNumberForRegion(phone, "IN"));
    assertFalse(phoneNumberUtil.isValidNumberForRegion(phone, "US"));
    assertTrue(phoneNumberUtil.isValidNumber(phoneNumberUtil.getExampleNumber("IN")));
}

Here, the number is validated when we did not specify a region, and also when we did.

3.5. isNumberGeographical​

This method checks if a given number has geography or region associated with it:

@Test
public void givenPhoneNumber_whenNumberGeographical_thenValid() throws NumberParseException {
    
    PhoneNumber phone = phoneNumberUtil.parse("+911234567890", "IN");
    assertTrue(phoneNumberUtil.isNumberGeographical(phone));

    phone = new PhoneNumber().setCountryCode(1).setNationalNumber(2530000L);
    assertFalse(phoneNumberUtil.isNumberGeographical(phone));

    phone = new PhoneNumber().setCountryCode(800).setNationalNumber(12345678L);
    assertFalse(phoneNumberUtil.isNumberGeographical(phone));
}

Here, in the first assert above, we gave the phone number in an international format with the region code, and the method returned true. The second assert uses a local number from the USA, and the third one a toll-free number. So the API returned false for these two.

4. Converting Phone Numbers into International Format (E.164)

Another common use case is converting a phone number into the E.164 international format, which is the globally recognized standard for representing phone numbers. In this format, a number includes the country calling code followed by the subscriber number, without any additional formatting symbols such as spaces, parentheses, or dashes.

For example, a U.S. number written as (415) 555-2671 would be represented as +14155552671 in E.164 format.

The PhoneNumberUtil class provides a convenient method to perform this conversion using its format() API. To do this, we first parse the number using the parse() method, providing the local region as context, and then format it using PhoneNumberFormat.E164 as the desired output format:

@Test
public void givenUSPhoneNumber_whenFormattedToE164_thenReturnsCorrectInternationalFormat() throws NumberParseException {
    PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();

    PhoneNumber number = phoneNumberUtil.parse("(415) 555-2671", "US");
    String e164Format = phoneNumberUtil.format(number, PhoneNumberUtil.PhoneNumberFormat.E164);

    assertEquals("+14155552671", e164Format);
}

In the example above, we first parse a U.S. local phone number by specifying the region code “US”. The library then interprets the number correctly and, when formatted using the E164 option, returns the normalized international version that includes the +1 country prefix and removes all local formatting.

The same approach can be applied to numbers from other countries. For instance, if we take an Indian mobile number such as 09876543210, we can parse it with the region code “IN” and convert it to the proper international format as shown below:

@Test
public void givenIndianPhoneNumber_whenFormattedToE164_thenReturnsCorrectInternationalFormat() throws NumberParseException {
    PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();

    PhoneNumber number = phoneNumberUtil.parse("09876543210", "IN");
    String e164Format = phoneNumberUtil.format(number, PhoneNumberUtil.PhoneNumberFormat.E164);

    assertEquals("+919876543210", e164Format);
}

In this case, the library automatically recognizes that the number belongs to India, adds the country code +91, and removes any unnecessary leading zeros or separators. The final result strictly follows the E.164 format, which makes it ideal for use in systems that handle international communication.

Converting phone numbers into E.164 format is handy when storing phone numbers in a database or when working with APIs that require globally standardized formats, such as SMS gateways or telephony services. It ensures that every number is stored in a consistent, unambiguous form, regardless of the country or the end user’s input style.

5. Conclusion

In this tutorial, we saw some of the functionality offered by libphonenumber to format and validate phone numbers using code samples.

This is a rich library that offers many more utility functions and takes care of most of our application needs for formatting, parsing, and validating 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 – LS – NPI (cat=Java)
announcement - icon

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

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)