VOOZH about

URL: https://www.baeldung.com/javax-measure

⇱ Introduction to javax.measure | Baeldung


πŸ‘ Image
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)
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 article, we’ll introduce the Units of Measurement API – which provides a unified way of representing measures and units in Java.

While working with a program containing physical quantities, we need to remove the uncertainty about units used. It’s essential that we manage both the number and its unit to prevent errors in calculations.

JSR-363 (formerly JSR-275 or javax.measure library) helps us save the development time, and at the same time, makes the code more readable.

2. Maven Dependencies

Let’s simply start with the Maven dependency to pull in the library:

<dependency>
 <groupId>javax.measure</groupId>
 <artifactId>unit-api</artifactId>
 <version>1.0</version>
</dependency>

The latest version can be found over on Maven Central.

The unit-api project contains a set of interfaces that define how to work with quantities and units. For the examples, we’ll use the reference implementation of JSR-363, which is unit-ri:

<dependency>
 <groupId>tec.units</groupId>
 <artifactId>unit-ri</artifactId>
 <version>1.0.3</version>
</dependency>

3. Exploring the API

Let’s have a look at the example where we want to store water in a tank.

The legacy implementation would look like this:

public class WaterTank {
 public void setWaterQuantity(double quantity);
}

As we can see, the above code does not mention the unit of quantity of water and is not suitable for precise calculations because of the presence of the double type.

If a developer mistakenly passes the value with a different unit of measure than the one we’re expecting, it can lead to serious errors in calculations. Such errors are very hard to detect and resolve.

The JSR-363 API provides us with the Quantity and Unit interfaces, which resolve this confusion and leave these kinds of errors out of our program’s scope.

3.1. Simple Example

Now, let’s explore and see how this can be useful in our example.

As mentioned earlier, JSR-363 contains the Quantity interface which represents a quantitative property such as volume or area. The library provides numerous sub-interfaces that model the most commonly used quantifiable attributes. Some examples are: Volume, Length, ElectricCharge, Energy, Temperature.

We can define the Quantity<Volume> object, which should store the quantity of water in our example:

public class WaterTank {
 public void setCapacityMeasure(Quantity<Volume> capacityMeasure);
}

Besides the Quantity interface, we can also use the Unit interface to identify the unit of measurement for a property. Definitions for often used units can be found in the unit-ri library, such as: KELVIN, METRE, NEWTON, CELSIUS.

An object of type Quantity<Q extends Quantity<Q>> has methods for retrieving the unit and value: getUnit() and getValue().

Let’s see an example to set the value for the quantity of water:

@Test
public void givenQuantity_whenGetUnitAndConvertValue_thenSuccess() {
 WaterTank waterTank = new WaterTank();
 waterTank.setCapacityMeasure(Quantities.getQuantity(9.2, LITRE));
 assertEquals(LITRE, waterTank.getCapacityMeasure().getUnit());

 Quantity<Volume> waterCapacity = waterTank.getCapacityMeasure();
 double volumeInLitre = waterCapacity.getValue().doubleValue();
 assertEquals(9.2, volumeInLitre, 0.0f);
}

We can also convert this Volume in LITRE to any other unit quickly:

double volumeInMilliLitre = waterCapacity
 .to(MetricPrefix.MILLI(LITRE)).getValue().doubleValue();
assertEquals(9200.0, volumeInMilliLitre, 0.0f);

But, when we try to convert the amount of water into another unit – which is not of type Volume, we get a compilation error:

// compilation error
waterCapacity.to(MetricPrefix.MILLI(KILOGRAM));

3.2. Class Parameterization

To maintain the dimension consistency, the framework naturally takes advantage of generics.

Classes and interfaces are parameterized by their quantity type, which makes it possible to have our units checked at compile time. The compiler will give an error or warning based on what it can identify:

Unit<Length> Kilometer = MetricPrefix.KILO(METRE);
Unit<Length> Centimeter = MetricPrefix.CENTI(LITRE); // compilation error

There’s always a possibility of bypassing the type check using the asType() method:

Unit<Length> inch = CENTI(METER).times(2.54).asType(Length.class);

We can also use a wildcard if we are not sure of the type of quantity:

Unit<?> kelvinPerSec = KELVIN.divide(SECOND);

4. Unit Conversion

Units can be retrieved from SystemOfUnits. The reference implementation of the specification contains the Units implementation of the interface which provides a set of static constants that represent the most commonly used units.

In addition, we can also create an entirely new custom unit or create a unit by applying algebraic operations on existing units.

The benefit of using a standard unit is that we don’t run into the conversion pitfalls.

We can also use prefixes, or multipliers from the MetricPrefix class, like KILO(Unit<Q> unit) and CENTI(Unit<Q> unit), which are equivalent to multiply and divide by a power of 10 respectively.

For example, we can define β€œKilometer” and β€œCentimeter” as:

Unit<Length> Kilometer = MetricPrefix.KILO(METRE);
Unit<Length> Centimeter = MetricPrefix.CENTI(METRE);

These can be used when a unit we want is not available directly.

4.1. Custom Units

In any case, if a unit doesn’t exist in the system of units, we can create new units with new symbols:

  • AlternateUnit – a new unit with the same dimension but different symbol and nature
  • ProductUnit – a new unit created as the product of rational powers of other units

Let’s create some custom units using these classes. An example of AlternateUnit for pressure:

@Test
public void givenUnit_whenAlternateUnit_ThenGetAlternateUnit() {
 Unit<Pressure> PASCAL = NEWTON.divide(METRE.pow(2))
 .alternate("Pa").asType(Pressure.class);
 assertTrue(SimpleUnitFormat.getInstance().parse("Pa")
 .equals(PASCAL));
}

Similarly, an example of ProductUnit and its conversion:

@Test
public void givenUnit_whenProduct_ThenGetProductUnit() {
 Unit<Area> squareMetre = METRE.multiply(METRE).asType(Area.class);
 Quantity<Length> line = Quantities.getQuantity(2, METRE);
 assertEquals(line.multiply(line).getUnit(), squareMetre);
}

Here, we have created a squareMetre compound unit by multiplying METRE with itself.

Next, to the types of units, the framework also provides a UnitConverter class, which helps us convert one unit to another, or create a new derived unit called TransformedUnit.

Let’s see an example to turn the unit of a double value, from meters to kilometers:

@Test
public void givenMeters_whenConvertToKilometer_ThenConverted() {
 double distanceInMeters = 50.0;
 UnitConverter metreToKilometre = METRE.getConverterTo(MetricPrefix.KILO(METRE));
 double distanceInKilometers = metreToKilometre.convert(distanceInMeters );
 assertEquals(0.05, distanceInKilometers, 0.00f);
}

To facilitate unambiguous electronic communication of quantities with their units, the library provides the UnitFormat interface, which associates system-wide labels with Units.

Let’s check the labels of some system units using the SimpleUnitFormat implementation:

@Test
public void givenSymbol_WhenCompareToSystemUnit_ThenSuccess() {
 assertTrue(SimpleUnitFormat.getInstance().parse("kW")
 .equals(MetricPrefix.KILO(WATT)));
 assertTrue(SimpleUnitFormat.getInstance().parse("ms")
 .equals(SECOND.divide(1000)));
}

5. Performing Operations With Quantities

The Quantity interface contains methods for the most common mathematical operations: add(), subtract(), multiply(), divide(). Using these, we can perform operations between Quantity objects:

@Test
public void givenUnits_WhenAdd_ThenSuccess() {
 Quantity<Length> total = Quantities.getQuantity(2, METRE)
 .add(Quantities.getQuantity(3, METRE));
 assertEquals(total.getValue().intValue(), 5);
}

The methods also verify the Units of the objects they are operating on. For example, trying to multiply meters with liters will result in a compilation error:

// compilation error
Quantity<Length> total = Quantities.getQuantity(2, METRE)
 .add(Quantities.getQuantity(3, LITRE));

On the other hand, two objects expressed in units that have the same dimension can be added:

Quantity<Length> totalKm = Quantities.getQuantity(2, METRE)
 .add(Quantities.getQuantity(3, MetricPrefix.KILO(METRE)));
assertEquals(totalKm.getValue().intValue(), 3002);

In this example, both meter and kilometer units correspond to the Length dimension so they can be added. The result is expressed in the unit of the first object.

6. Conclusion

In this article, we saw that Units of Measurement API gives us a convenient measurement model. And, apart from the usage of Quantity and Unit, we also saw how convenient it is to convert one unit to another, in a number of ways.

For further information, you can always check out the project here.

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)