Ok, I'm late on this and an answer is already accepted, but I wonder why nobody has used a clean and simple counter yet?
public class Counter
{
static Counter[] vtab = new Counter[]
{
new Counter(),
new Counter() { public void print( int first, int last ) {} }
};
public void print( int first, int last )
{
vtab[ ( last - first - 1 ) >>> 31 ].print( first, last - 1 );
System.out.println( last );
}
public static void main( String[] args )
{
vtab[ 0 ].print( 1, 100 );
}
}
Thread safe, configurable, no exceptions, no dependance on API side effects, just plain OOP and some trivial math.
For those not familiar with binary operators here is how it works:
The ( x >>> n )
expression moves all bits of the integer value x
to the right by n
places. Lower bits simply fall off the right side by this operation and new bits that come in from the left side are always 0
.
So the effect of ( x >>> 31 )
is to move the highest bit of x
to the lowest place and to set all other bits of x
to 0
. The result is now always either 0
or 1
for all possible values of x
.
As the highest bit of an int
is the sign bit which is 0
for positive values and 1
for negative values, the expression ( x >>> 31 )
evaluates to 0
for all positve values of x
and to 1
for all negative values of x
.
Now if both first
and last
are positive numbers and if last
is greater than first
, the result of ( last - first - 1 )
will be >= 0
and if last == first
it will be -1
.
So ( ( last - first - 1 ) >>> 31 )
evaluates to 0
if last
is greater than first
and becomes 1
if they are equal.
Now this value 0/1
is used to switch between the 2 implementations of print( int first, int last )
based on the comparision of first
and last
. At first the recursion takes place without printing anything. print( 1, 100 )
calls print( 1, 99 )
and so on... until last
equals first
which causes a switch to the other implementation of print
which in turn does nothing at all. So now the stack unwinds again and the values are printed on the way down in ascending order and the invocation of vtab[ 0 ].print( 1, 100 )
finishes normally.