Search code examples
javapackagedirectorysubdirectory

Package name is different than the folder structure but still Java code compiles


I am using Notepad++ to write my Java code and Command Prompt to compile and run it. Following is my sample Java code,

    package abraKadabra;

    public class SuperClass{
       protected int anInstance;

       public static void main(String [] abc){
           System.out.println("Hello");
       }
    }

However, this file is in the following folder structure :

"usingprotected\superPkg" (usingProtected is a folder somewhere in the hierarchy in C:)

So, my package name here should be something like usingProtected.superPkg instead of abraKadabra as I wrote it.

But, when I compile this Java code from command prompt, it compiles fine with no error or warnings. Why is it so? Shouldn't the package name adhere to the folder structure? And if it should, how would it adhere?

For e.g. if my package name is usingProtected.superPkg, will the compiler check in the reverse order. The present working directory should be superPkg, then the parent directory should be usingProtected and its done. Is it how it checks the folder structure with package name?


Solution

  • After experimenting a bit, I got the way how to use package name and run Java class files from command prompt.

    Suppose following is my Java source file:-

        package mySample;
    
    
        public abstract class Sample{
            public static void main(String... a){
               System.out.println("Hello ambiguity");
            }
        }
    

    This file is in directory "D:\Code N Code\CommandLine".

    Now, when compile the source code (by going to the above directory from cmd) using following command:-

        javac -d . Sample.java
    

    This automatically creates "mySample" folder in my current directory. So, my class file Sample.class is present in directory "D:\Code N Code\CommandLine\mySample". Compiler created this new folder "mySample" from the package name that I gave in my source code.

    So if I had given my package name to be "package com.mySample", compiler would create two directories and place my class file in "D:\Code N Code\CommandLine\com\mySample".

    Now, I am still in the present working directory i.e. in "D:\Code N Code\CommandLine". And to run my class file, I give the following command:

        java mySample.Sample
    

    So, I give the complete hierarchy of package and then the class name. The Java Interpreter will search the current directory for "mySample" directory and in that for "Sample.class". It gets it right and runs it successfully. :)

    Now, when I asked that why it compiles my wrong package source code, it would compile the code successfully though, but it gives NoClassDefFoundError when I run my class file. So above method can be used to use package names from command line.