Search code examples
javacompilationjavac

How does Javac work for multiple files, directories, classes and source?


I'm trying to figure out how javac works with regard to stuff like sourcepath, classpath and prebuilt classes etc. I'm trying to read the documentation, but can't really make sense of it.

I've tried to think of some sample cases below.

  1. If I'm compiling a single file onlyfile.java which has no dependencies, which has 2 classes A and B , and class A uses class B , does class B need to be defined/declared before A ? Or is javac smart and does multiple passes or something like that ?

  2. root.java uses another class in a file file2.java located in the same folder. If I execute javac root.java , how does javac know to search the folder for the class file and if not found , for source file instead ?

  3. How does the above work if the file2 is located in a subdirectory ?

EDIT: I read somewhere that import is just a way to cut down on typing rather than "loading" anything like in python. Suppose that I'm building only 1 java file which uses multiple other classes, and that these class files already exist. Without import, the a.b.c.d part of the class object already tells me where to search for the class file, then why a cp option ?


Solution

  • 1) If you compile class A which uses class B then class B will be compelled as well. If you compile class B (which is used inside A, but A is not used inside B), class A will not be compelled. Find more details end examples here.

    2) javac searches inside source-path and class-path. If you run javac without arguments like javac A.java it sets classpath and sourcepath to current directory. If requested class is not found neither in classpath nor in sourcepath you'll have compilation error.

    3) Java has strict rules for project structure. You can't simply place source file to another folder without updating file content.

    Every folder in the project should have folder hierarchy with respect of package declaration.

    Definition: A package is a grouping of related types providing access protection and name space management.

    for instance if you have class A.java with package declaration like this

    package com.mycompany;
    

    The corresponding folder structure should look like this:

    com/mycompany/A.java
    

    If you follow this rules compiler will be able to resolve dependencies just like I explained in #1. Find more information here.