Wednesday, May 14, 2008

Index overflow in Java for loop

The following little code snippet shows the overflow of for loop index in Java.

public class Out {
public static void main(String[] ars) {
for(int i = 0; i <= 2147483647 ; i+=100000000 )
{
System.out.println( i + "\n" );
}
}
}

You may expect that the iteration count is 22. But it is not true. i is 2100000000 after the 22nd iteration. Then 100000000 is added to i(2100000000) again. 2200000000 is bigger than 2147483647. So int overflow will happen. i will become a negative integer. So the loop will continue.

For details of loop index overflow, you can refer to Programming Language Pragmatics.

Friday, May 2, 2008

Genenared methods values and valueOf for Enum

I have recently tried Java Enum when doing software development. The following code is an example:

public Enum FooType {
ABC, DEF;
}

I found two methods valueOf and values in the Javadoc for my enum code. I did not write these 2 methods. And it's superclass java.lang.Enum<FooType> also does not have these 2 methods. Then I checked JLS 3.0. 8.9 Enums says these 2 methods are automatically generated. It is a little magic. One Java class can has methods which do not exist as source code. Too many magic which do not have a consistent rationale can make a language hard to learn and use.