How to Convert Floor Division to Ceiling Division

Jan
7

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

Oct
21

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:

@Annotation
[ public | protected | private ]
static
abstract
final
native
synchronized
[ transient | volatile ]
strictfp
[ int | long | byte | class | enum | interface | etc. ]

* http://docs.oracle.com/javase/specs/jls/se7/html/jls-18.html

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