Partner – Microsoft – NPI (cat=Java)
announcement - icon

Microsoft JDConf 2024 conference is getting closer, on March 27th and 28th. Simply put, it's a free virtual event to learn about the newest developments in Java, Cloud, and AI.

Josh Long and Mark Heckler are kicking things off in the keynote, so it's definitely going to be both highly useful and quite practical.

This year’s theme is focused on developer productivity and how these technologies transform how we work, build, integrate, and modernize applications.

For the full conference agenda and speaker lineup, you can explore JDConf.com:

>> RSVP Now

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.

And, as always, the entire code is available over on GitHub.

Course – LS (cat=Java)

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

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!