Over a million developers have joined DZone.

The Great Effect of Small Details

DZone 's Guide to

The Great Effect of Small Details

This all goes to show that engineering skills are the most visible at the end points.

· Performance Zone ·
Free Resource

Question: How many lines are written with the following code fragment?

public static void main(String[] args){
for (int i = Integer.MIN_VALUE; i <= Integer.MAX_VALUE; i++) {

A. Infinite

B. (2147483647 *2) +1

C. 0

D. Compilation error

Most of us, if we do not pay attention, may think the answer is B. However, the following code fragment can convince us that the answer is A.

public static void main(String[] args){
System.out.println(Integer.MAX_VALUE + 1);





In the above code fragment, the code runs as expected until the variable i equals Integer.MAX_VALUE. At that point, the value of i (which is Integer.MAX_VALUE) is printed. After passing the control of current iteration, i is incremented by one. We may think the new value of i is Integer.MAX_VALUE + 1, but no; it is Integer.MIN_VALUE. Since Integer.MIN_VALUE is less than Integer.MAX_VALUE, iteration goes on infinitely.

In order to understand this situation, we have to dive deep into the world of bytes and bits. In Java, int data type can hold values up to 32 bits. The lowest value that it can hold is Integer.MIN_VALUE, which is -2147483648, whose binary representation is 1000 0000 0000 0000 0000 0000 0000 0000. The left-most bit of this representation is the sign bit with 0, which indicates positive, and with 1, which indicates negative. In the previous value, the sign bit is 1. So, as we can see, Java uses only 31 bits to store the number.

Image title

With this knowledge, let’s add one to Integer.MAX_VALUE 2147483647, whose binary representation is 0111 1111 1111 1111 1111 1111 1111 1111:

Image title

As it is seen, the result is Integer.MIN_VALUE.

Thinking the above situation, for example, if we create a JPA entity class with an identifier property of type java.lang.Integer, our code works for a while (perhaps even years). But as the database size grows, the above problem occurs by their range. An integer would work for almost two months if we generate a new identifier each millisecond with no gaps, and a long would last for about 300 million years.

Consequently, choosing right data types may be a simple detail, but can also cause great effects.

By this way, I want to quote, my university professor's statement here: “Engineering skills are visible at the end points.”

performance ,integers ,software engineering

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}