How to Convert Floor Division to Ceiling Division


Today I found an elegant way to implement ceiling division.

Using Java, the following code results in an integer result of ceil(5/6):

int div = (int)Math.ceil(5 / (double)6);

A simpler, more elegant solution the doesn't require the Math library would be:

int div = (5 + 6 - 1) / 6;

Here's the solution generally:

int ceiling = (numerator + denominator - 1) / denominator;

However, one must be careful since there is a possibility here for an overflow. One way to prevent an overflow would be to use long instead of int.

On a related note, to convert floor division to rounding division, you can use the following:

int rounded = (numerator + denominator / 2) / denominator;

You may read more about this at its source.

Java Modifier Keyword Order


After doing some Java development with Sonar, I soon realized that there is a reasonable order that some modifiers should be in. This piqued my interest, so I did some research. This is what I found:

According to the Java Language Specification* the order of modifiers is encouraged be:

[ public | protected | private ]
[ transient | volatile ]
[ int | long | byte | class | enum | interface | etc. ]


It is important to note that the order of most modifiers does not matter, but it is good practice to remain consistent throughout your development.

Tags: #Java Comments: Loading comment count... Author: Seth Westphal