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

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Introduction

In this tutorial, we’ll explore various approaches to validating geo coordinates and their accuracy in Java.

2. Understand Geo Coordinates

Geo coordinates are typically expressed as latitude and longitude values, pinpointing locations on our spherical Earth. Latitude measures the distance north or south of the equator and ranges from -90° (South Pole) to 90° (North Pole). On the other hand, longitude measures the distance east or west of the prime meridian and spans -180° (International Date Line) to 180°.

3. Understanding Precision and Accuracy

When checking the validity of coordinates, one crucial factor to consider is the precision of the decimal places. The level of detail expressed by a coordinate and associated with a location is indicated by precision, which is represented by the number of decimal places.

Furthermore, rounding coordinates can cause inaccuracies, especially in applications sensitive to proximity. For example, mapping a building might require coordinates accurate to five decimal places (approximately one meter), while city-level mapping might only need two decimal places (approximately one kilometer).

4. Latitude and Longitude Formats

Understanding the various formats is fundamental for both input and validation of coordinates.

4.1. Decimal Degrees (DD)

Geo coordinates are commonly represented in decimal degrees, where both latitude and longitude are expressed as decimal values. In the DD format, valid latitude values typically range from -90 to 90, while valid longitude values range from -180 to 180. For example, the coordinates for the Eiffel Tower in Paris are approximately 48.8588445 (latitude) and 2.2943506 (longitude).

4.2. Degrees, Minutes, and Seconds (DMS)

The DMS format involves degrees, minutes, and seconds, and latitude and longitude are expressed as degrees. Each degree is further divided into 60 minutes, and each minute can optionally be divided into 60 seconds. Symbols such as ° (degree), ‘ (minute), and ” (second) are used to separate these components. For instance, the coordinates for the Statue of Liberty are 40°41’21.7″N (latitude) and 74°02’40.7″W (longitude).

4.3. Military Grid Reference System (MGRS)

MGRS is another coordinate format used to specify locations on the Earth’s surface. It divides the world into grid zones and provides a concise representation of them. Each section is a 6° wide zone, numbered 1 to 60, further divided into 100,000-meter squares identified by two-letter codes. Within each square, precise positions are given by “Easting” and “Northing”, both measured in meters. For example, the Great Wall of China’s Badaling section can be located as 50TMK6356175784.

5. Basic Validation With Regular Expressions

Regular expressions are powerful tools for pattern matching. We can craft a regex pattern to identify valid coordinate formats using Java’s Pattern and Matcher classes.

The first regex is crafted for DD format, where two decimal numbers are separated by a comma, with an optional space:

public static final String DD_COORDINATE_REGEX = "^(-?\\d+\\.\\d+)(\\s*,\\s*)?(-?\\d+\\.\\d+)$";

The second regex is built to handle the DMS format. It checks for two sets of coordinates, including degrees, minutes, seconds, and cardinal directions (N, S, W, or E), allowing for flexibility in symbol usage:

public static final String DMS_COORDINATE_REGEX = 
  "^(\\d{1,3})°(\\d{1,2})\'(\\d{1,2}(\\.\\d+)?)?\"?([NSns])(\\s*,\\s*)?
    (\\d{1,3})°(\\d{1,2})\'(\\d{1,2}(\\.\\d+)?)?\"?([WEwe])$";

The final regex caters to MGRS coordinates. The code validates patterns that consist of a UTM zone represented by two digits, a latitude band using alphabetical characters (excluding I and O), followed by two to ten digits arranged in even pairs:

public static final String MGRS_COORDINATE_REGEX = 
  "^\\d{1,2}[^IO]{3}(\\d{10}|\\d{8}|\\d{6}|\\d{4}|\\d{2})$";

Let’s define utility methods to validate each format:

boolean validateCoordinates(String coordinateString) {
    return isValidDDFormat(coordinateString) || isValidDMSFormat(coordinateString) || isValidMGRSFormat(coordinateString);
}

boolean isValidDDFormat(String coordinateString) {
    return Pattern.compile(DD_COORDINATE_REGEX).matcher(coordinateString).matches();
}

boolean isValidDMSFormat(String coordinateString) {
    return Pattern.compile(DMS_COORDINATE_REGEX).matcher(coordinateString).matches();
}

boolean isValidMGRSFormat(String coordinateString) {
    return Pattern.compile(MGRS_COORDINATE_REGEX).matcher(coordinateString).matches();
}

Regular expressions are useful for basic validation but cannot guarantee the correctness of coordinates. For instance, the DD regex doesn’t validate whether the coordinates fall within Earth’s latitude and longitude ranges.

6. Custom Validation Logic for Complex Scenarios

To handle complex scenarios, let’s break down the validation process into smaller, more explicit steps.

6.1. Decimal Degrees

Let’s improve the isValidDDFormat() method to handle edge cases such as non-numerical inputs and invalid coordinates:

boolean isValidDDFormat(String coordinateString) {
    try {
        String[] parts = coordinateString.split(",");
        if (parts.length != 2) {
            return false;
        }

        double latitude = Double.parseDouble(parts[0].trim());
        double longitude = Double.parseDouble(parts[1].trim());
        if (latitude < -90 || latitude > 90 || longitude < -180 || longitude > 180) {
            return false;
        }

        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}

The String.split() method splits the coordinates using commas and spaces as delimiters to accommodate different input formats. This ensures there are exactly two parts (latitude and longitude). We then validate that the numeric values fall within the specified ranges.

The NumberFormatException is caught to handle cases where parsing to doubles fails.

6.2. Degrees, Minutes, and Seconds

Next, let’s improve the isValidDMSFormat() method to split the coordinate string into degrees, minutes, seconds, and hemisphere parts, and validate each one accordingly:

boolean isInvalidLatitude(int degrees, int minutes, double seconds, String hemisphere) {
    return degrees < 0 || degrees > 90 || minutes < 0 || minutes >= 60 || seconds < 0 || seconds >= 60 || 
	  (!hemisphere.equalsIgnoreCase("N") && !hemisphere.equalsIgnoreCase("S"));
}

The isInvalidLatitude() method checks whether the provided latitude components are outside of the valid ranges. It returns true (invalid) if any of the following invalid conditions are met:

  • Latitude degrees are less than 0 or greater than 90
  • Latitude minutes are less than 0 or greater than or equal to 60
  • Latitude seconds are less than 0 or greater than or equal to 60
  • Hemisphere is not “N” (North) or “S” (South)

Similarly, we’ll create the equivalent validation method for longitude:

boolean isInvalidLongitude(int degrees, int minutes, double seconds, String hemisphere) {
    return degrees < 0 || degrees > 180 || minutes < 0 || minutes >= 60 || seconds < 0 || seconds >= 60 ||
      (!hemisphere.equalsIgnoreCase("E") && !hemisphere.equalsIgnoreCase("W"));
}

The isInvalidLongitude() method checks the provided longitude components, returning true (invalid) if any of the following invalid conditions are met:

  • Longitude degrees are less than 0 or greater than 180
  • Longitude minutes are less than 0 or greater than or equal to 60
  • Longitude seconds are less than 0 or greater than or equal to 60
  • Hemisphere is not “E” (East) or “W” (West)

Lastly, let’s leverage both validation methods to validate DMS coordinates:

boolean isValidDMSFormatWithCustomValidation(String coordinateString) {
    try {
        String[] dmsParts = coordinateString.split("[°',]");
        if (dmsParts.length > 6) {
            return false;
        }

        int degreesLatitude = Integer.parseInt(dmsParts[0].trim());
        int minutesLatitude = Integer.parseInt(dmsParts[1].trim());
        String[] secondPartsLatitude = dmsParts[2].split("\"");
        double secondsLatitude = secondPartsLatitude.length > 1 ? Double.parseDouble(secondPartsLatitude[0].trim()) : 0.0;
        String hemisphereLatitude = secondPartsLatitude.length > 1 ? secondPartsLatitude[1] : dmsParts[2];

        int degreesLongitude = Integer.parseInt(dmsParts[3].trim());
        int minutesLongitude = Integer.parseInt(dmsParts[4].trim());
        String[] secondPartsLongitude = dmsParts[5].split("\"");
        double secondsLongitude = secondPartsLongitude.length > 1 ? Double.parseDouble(secondPartsLongitude[0].trim()) : 0.0;
        String hemisphereLongitude = secondPartsLongitude.length > 1 ? secondPartsLongitude[1] : dmsParts[5];

        if (isInvalidLatitude(degreesLatitude, minutesLatitude, secondsLatitude, hemisphereLatitude) ||
          isInvalidLongitude(degreesLongitude, minutesLongitude, secondsLongitude, hemisphereLongitude)) {
            return false;
        }

        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}

The isValidDMSFormatWithCustomValidation() method splits the input into its latitudinal and longitudinal components and validates them separately using the helper methods. If all checks pass, the DMS format is considered valid, and the method returns true (valid).

7. Conclusion

In this article, we’ve explored two distinct approaches to validating geo coordinates. Regular expressions offer a quick solution for basic validation, while the custom validation logic offers flexibility and error feedback, making it suitable for complex scenarios.

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.

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