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

In this tutorial, we’re going to describe the Math class that provides helpful static methods for performing numeric operations such as exponential, logarithm, etc.

2. Basic Math Functions

The first set of methods we’ll cover are the basic math functions such as the absolute value, the square root, the maximum or the minimum between two values.

2.1. abs()

The abs() method returns the absolute value of a given value:

Math.abs(-5); // returns 5

Likewise, of others that we’ll see next, abs() accepts as a parameter an int, long, float or double and returns the relative one.

2.2. pow()

Calculates and returns the value of the first argument raised to the power of the second one:

Math.pow(5,2); // returns 25

We discuss this method in more detail in here.

2.3. sqrt()

Returns the rounded positive square root of a double:

Math.sqrt(25); // returns 5

If the argument is NaN or less than zero, the result is NaN.

2.4. cbrt()

Similarly, cbrt() returns the cube root of a double:

Math.cbrt(125); // returns 5

2.5. max()

As the method’s name suggests, it returns the maximum between two values:

Math.max(5,10); // returns 10

Here again, the method accepts int, long, float or double.

2.6. min() 

In the same way, min() returns the minimum between two values:

Math.min(5,10); // returns 5

2.7. random()

Returns a pseudorandomly double greater than or equal to 0.0 and less than 1.0:

double random = Math.random()

To do this, the method creates a single instance of java.util.Random() number generator when it is called for the first time. 

After that, for all calls to this method, the same instance is used. Note that, the method is synchronized, thus can be used by more than one thread.

We can find more examples of how to generate a random in this article.

2.8. signum()

Is useful when we have to know the value’s sign:

Math.signum(-5) // returns -1

This method returns 1.0 if the argument is greater than zero or -1.0 otherwise. If the argument is zero positive or zero negative, the result is the same as the argument.

The input can be a float or a double.

2.9. copySign()

Accepts two parameters and returns the first argument with the sign of the second argument:

Math.copySign(5,-1); // returns -5

Arguments can also be float or double.

3. Exponential and Logarithmic Functions

In addition to the basic math functions, the Math class contains methods to solve exponential and logarithmic functions.

3.1. exp()

The exp() method receives a double argument and returns Euler’s number raised to the power of the argument (ex):

Math.exp(1); // returns 2.718281828459045

3.2. expm1()

Similar to the above method, expm1() computes the Euler’s number raised to the power of the argument received, but it adds -1 (ex -1):

Math.expm1(1); // returns 1.718281828459045

3.3. log()

Returns the natural logarithm of a double value:

Math.log(Math.E); // returns 1

3.4. log10()

It returns the logarithm in base 10 of the argument:

Math.log10(10); // returns 1

3.5. log1p()

Likewise the log(), but it adds 1 to the argument ln(1 + x):

Math.log1p(Math.E); // returns 1.3132616875182228

4. Trigonometric Functions

When we have to work with geometric formulas, we always need trigonometric functions; the Math class provides these for us.

4.1. sin()

Receives a single, double argument that represents an angle (in radians) and returns the trigonometric sine:

Math.sin(Math.PI/2); // returns 1

4.2. cos()

In the same way, cos() returns the trigonometric cosine of an angle (in radians):

Math.cos(0); // returns 1

4.3. tan()

Returns the trigonometric tangent of an angle (in radians):

Math.tan(Math.PI/4); // returns 1

4.4. sinh(), cosh(), tanh()

They return respectively the hyperbolic sine, hyperbolic cosine and hyperbolic tangent of a double value:

Math.sinh(Math.PI);

Math.cosh(Math.PI);

Math.tanh(Math.PI);

4.5. asin()

Returns the arc sine of the argument received:

Math.asin(1); // returns pi/2

The result is an angle in the range –pi/2 to pi/2.

4.6. acos()

Returns the arc cosine of the argument received:

Math.acos(0); // returns pi/2

The result is an angle in the range 0 to pi.

4.7. atan()

Returns the arc tangent of the argument received:

Math.atan(1); // returns pi/4

The result is an angle in the range –pi/2 to pi/2.

4.8. atan2()

Finally, atan2() receives the ordinate coordinate y and the abscissa coordinate x, and returns the angle ϑ from the conversion of rectangular coordinates (x,y) to polar coordinates (r, ϑ):

Math.atan2(1,1); // returns pi/4

4.9. toDegrees()

This method is useful when we need to convert radians to degrees:

Math.toDegrees(Math.PI); // returns 180

4.10. toRadians()

On the other hand toRadians() is useful to do the opposite conversion:

Math.toRadians(180); // returns pi

Remember that most of the methods we have seen in this section accept the argument in radians, thus, when we have an angle in degrees, this method should be used before using a trigonometric method.

For more examples, have a look in here.

5. Rounding and Other Functions

Finally, let’s have a look at rounding methods.

5.1. ceil()

ceil() is helpful when we have to round an integer to the smallest double value that is greater than or equal to the argument:

Math.ceil(Math.PI); // returns 4

In this article, we use this method to round up a number to the nearest hundred.

5.2. floor()

To round a number to the largest double that is less than or equal to the argument we should use floor():

Math.floor(Math.PI); // returns 3

5.3. getExponent()

Returns an unbiased exponent of the argument.

The argument can be a double or a float:

Math.getExponent(333.3); // returns 8

Math.getExponent(222.2f); // returns 7

5.4. IEEEremainder()

Computes the division between the first (dividend) and the second (divisor) argument and returns the remainder as prescribed by the IEEE 754 standard:

Math.IEEEremainder(5,2); // returns 1

5.5. nextAfter()

This method is useful when we need to know the neighboring of a double or a float value:

Math.nextAfter(1.95f,1); // returns 1.9499999

Math.nextAfter(1.95f,2); // returns 1.9500002

It accepts two arguments, the first is the value of which you want to know the adjacent number and the second is the direction.

5.6. nextUp()

Likewise the previous method, but this one returns the adjacent value only in the direction of a positive infinity:

Math.nextUp(1.95f); // returns 1.9500002

5.7. rint()

Returns a double that is the closest integer value of the argument:

Math.rint(1.95f); // returns 2.0

5.8. round()

Equally to the above method, but this one returns an int value if the argument is a float and a long value if the argument is a double:

int result = Math.round(1.95f); // returns 2

long result2 = Math.round(1.95) // returns 2

5.9. scalb()

Scalb is an abbreviation for a “scale binary”. This function executes one shift, one conversion and a double multiplication:

Math.scalb(3, 4); // returns 3*2^4

5.10. ulp()

The ulp() method returns the distance from a number to its nearest neighbors:

Math.ulp(1); // returns 1.1920929E-7
Math.ulp(2); // returns 2.3841858E-7
Math.ulp(4); // returns 4.7683716E-7
Math.ulp(8); // returns 9.536743E-7

5.11. hypot()

Returns the square root of the sum of squares of its argument:

Math.hypot(4, 3); // returns 5

The method calculates the square root without intermediate overflow or underflow.

In this article, we use this method to calculate the distance between two points.

6. Java 8 Math Functions

Java 8 introduced several new methods for arithmetic operations, overflow handling, and enhanced precision in mathematical calculations. This section provides an overview of these methods.

6.1. addExact()

The addExact() method adds two integers or longs and throws an ArithmeticException if the result overflows:

Math.addExact(100, 50);               // returns 150
Math.addExact(Integer.MAX_VALUE, 1);  // throws ArithmeticException

6.2. substractExact()

The subtractExact() method subtracts one integer or long from another, throwing an ArithmeticException if the result overflows:

Math.subtractExact(100, 50);           // returns 50
Math.subtractExact(Long.MIN_VALUE, 1); // throws ArithmeticException

6.3. incrementExact()

The incrementExact() method increments an integer or long by one. It throws an ArithmeticException if the result overflows:

Math.incrementExact(100);               // returns 101
Math.incrementExact(Integer.MAX_VALUE); // throws ArithmeticException

6.4. decrementExact()

The decrementExact() method decrements an integer or long by one. It throws an ArithmeticException if the result overflows:

Math.decrementExact(100);            // returns 99
Math.decrementExact(Long.MIN_VALUE); // throws ArithmeticException

6.5. multiplyExact()

The multiplyExact() method multiplies two integers or longs. It throws an ArithmeticException if the result overflows.

Math.multiplyExact(100, 5);            // returns 500
Math.multiplyExact(Long.MAX_VALUE, 2); // throws ArithmeticException

6.6. negateExact()

The negateExact() method changes the sign of the parameter, throwing an ArithmeticException in case of overflow.

In this case, we have to think about the internal representation of the value in memory to understand why there’s an overflow, as is not as intuitive as the rest of the “exact” methods:

Math.negateExact(100);               // returns -100
Math.negateExact(Integer.MIN_VALUE); // throws ArithmeticException

The second example requires an explanation as it’s not obvious: The overflow is due to the Integer.MIN_VALUE being −2.147.483.648, and on the other side the Integer.MAX_VALUE being 2.147.483.647 so the returned value doesn’t fit into an Integer by one unit.

6.7. floorDiv()

The floorDiv() method divides the first parameter by the second one, and then performs a floor() operation over the result, returning the Integer that is less or equal to the quotient:

Math.floorDiv(7, 2));  // returns 3

The exact quotient is 3.5 so floor(3.5) == 3.

Let’s look at another example:

Math.floorDiv(-7, 2)); // returns -4

The exact quotient is -3.5 so floor(-3.5) == -4.

6.8. floorMod()

This one is similar to the previous method floorDiv(), but applying the floor() operation over the modulus or remainder of the division instead of the quotient:

Math.floorMod(5, 3));  // returns 2

As we can see, the floorMod() for two positive numbers is the same as % operator. Let’s look at a different example:

Math.floorMod(-5, 3));  // returns 1

It returns 1 and not 2 because floorMod(-5, 3) is -2 and not -1.

6.9. nextDown()

The nextDown() method returns the immediately lower value for float or double types, providing precise control:

float f = Math.nextDown(3);  // returns 2.9999998
double d = Math.nextDown(3); // returns 2.999999761581421

7. Constants Fields

In addition to the methods, Math class declares two constant fields:

public static final double E

public static final double PI

Which indicate the closer value to the base of the natural logarithms, and the closer value to pi, respectively.

8. Conclusion

In this article, we’ve described the APIs that Java provides for mathematical operations.

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)