Wednesday, August 22, 2007

My Java Puzzle: does order of import statements in Java matter?

Probably everybody thinks that this question is stupid. We all know that in Java the order (sequence) of import statements does not matter at all.

Is it really the case?

Consider the example: (part of my almost original code simplified and renamed)

package demo;

import static demo.WhatThe.f;
import java.util.RandomAccess;

public class Demo {
public void x() {
f();
}
}

class WhatThe implements RandomAccess {
public static WhatThe f() {
return null;
}
}


Do you think it compiles? If you say yes - you are almost right. It compiles well with Eclipse compiler, but every Sun Java compiler fails with the error like this:

demo\Demo.java:14: cannot find symbol
symbol: class RandomAccess
class WhatThe implements RandomAccess {
^
1 error


Why you'll ask: see this bug.
And now if you use Sun compiler, just change the order of imports (swap the first import with the second) and, behold, it works now:


package demo;

import java.util.RandomAccess;
import static demo.WhatThe.f;

public class Demo {
public void x() {
f();
}
}

class WhatThe implements RandomAccess {
public static WhatThe f() {
return null;
}
}


Anybody said the order does not matter?... :)
Today I've lost 2 hours hunting for this problem amongst hundreds of java files and 3rd party jars. If wish to spare you the same...

Regards,

Wojtek

1 comment: