Is Java's import keyword for source files or binary files?

I know I can include a class or collection of classes in my Java project using the import statement.

For example, import java.io.utils.* imports (i.e. makes available for use in my Java program) all the classes in the java.io.utils package.

My question is, do the classes in an imported package need to be compiled? Or can packages also include uncompiled Java files? If it can be either, when can we use class files and when can we use Java files?

Jon Skeet
people
quotationmark

Import just means "make the imported classes available by their simple names" - you can remove imports entirely if you use fully-qualified names everywhere. It's definitely not like #include in C for example.

When you compile, if you try to refer to uncompiled code it will be compiled at that point, assuming the compiler can guess where to find the source code. The result never refers to uncompiled code, because the compiler needs to know what each type exposes.

As a complete example, construct the following file structure:

// src/foo/A.java
package foo;
import bar.*;

public class A {
    public static void main(String[] args) {
        B.sayHello();
    }
}

// src/bar/B.java
package bar;
public class B {
    public static void sayHello() {
        System.out.println("Hello");
    }
}

Then in the src directory, run:

javac foo/A.java

That will automatically compile bar/B.java - but wouldn't compile any other code that isn't referenced (potentially transitively).

I would strongly recommend against using this "compile on demand" behaviour anyway though - if you compile class A that depends on class B, it will compile B the first time, but after that if you change B and recompile A, the compiler won't recompile B. I would organize your code into appropriate projects, and always recompile a complete project at a time, adding a project's output directory to the classpath for a project that depends on it, rather than allowing compiling one project to recompile bits of another on demand.

(Note that this isn't talking about the incremental compilation that many IDEs support... that's a rather different matter, and is fine assuming it's been implemented properly.)

people

See more on this question at Stackoverflow