Reader small image

You're reading from  Java Coding Problems - Second Edition

Product typeBook
Published inMar 2024
PublisherPackt
ISBN-139781837633944
Edition2nd Edition
Right arrow
Author (1)
Anghel Leonard
Anghel Leonard
author image
Anghel Leonard

Anghel Leonard is a Chief Technology Strategist and independent consultant with 20+ years of experience in the Java ecosystem. In daily work, he is focused on architecting and developing Java distributed applications that empower robust architectures, clean code, and high-performance. Also passionate about coaching, mentoring and technical leadership. He is the author of several books, videos and dozens of articles related to Java technologies.
Read more about Anghel Leonard

Right arrow

21. Computing the quotient of the arguments and result overflow

Let’s start with two simple computations, as follows:

-4/-1 = 4, 4/-1 = -4

This is a very simple use case that works as expected. Now, let’s keep the divisor as -1, and let’s change the dividend to Integer.MIN_VALUE (-2,147,483,648):

int x = Integer.MIN_VALUE;
int quotient = x/-1; // -2,147,483,648

This time, the result is not correct. The int domain was overflowed because of |Integer.MIN_VALUE| > |Integer.MAX_VALUE|. It should be the positive 2,147,483,648, which doesn’t fit in the int domain. However, changing the x type from int to long will solve the problem:

long x = Integer.MIN_VALUE;
long quotient = x/-1; // 2,147,483,648

But the problem will reappear if, instead of Integer.MIN_VALUE, there is Long.MIN_VALUE:

long y = Long.MIN_VALUE; // -9,223,372,036,854,775,808
long quotient = y/-1;    // -9,223,372,036,854,775,808

Starting with JDK 18, the Math...

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Java Coding Problems - Second Edition
Published in: Mar 2024Publisher: PacktISBN-13: 9781837633944

Author (1)

author image
Anghel Leonard

Anghel Leonard is a Chief Technology Strategist and independent consultant with 20+ years of experience in the Java ecosystem. In daily work, he is focused on architecting and developing Java distributed applications that empower robust architectures, clean code, and high-performance. Also passionate about coaching, mentoring and technical leadership. He is the author of several books, videos and dozens of articles related to Java technologies.
Read more about Anghel Leonard