How can I compile classes in packages, to execute them later with "java Program" (without the package name)?

16,160

You better put the source codes on the directory source/myProgram and create a directory called build to put the .class files. Thus, you can compile and run this way:

javac source/myProgram/Program.java -d build
cd build
java myProgram/Program
Share:
16,160
FlamesPuck12
Author by

FlamesPuck12

Updated on June 05, 2022

Comments

  • FlamesPuck12
    FlamesPuck12 almost 2 years

    I have a quick question regarding javac and packages in Java.

    I have a simple program (we'll call it Program.java) which is currently in the following directory:

    • myRepository/myProgram

    In Program.java and other .java files in the myRepository/myProgram directory, I have declared package myProgram.* and also included import myProgram.*;.

    So when I type javac myProgram/Program.java, it compiles fine and it runs fine if I type java myProgram/Program.

    However, I'm trying to get the .class files to be produced in the myRepository directory, not myRepository/myProgram, which is where the source files are. I tried javac myProgram/Program.java -d .. which produces the .class files in myRepository directory, but when I try "java Program", it gives me the following error:

    Exception in thread "main" java.lang.NoClassDefFoundError: Program (wrong name: myProgram/Program).

    Is there any way way I could get .class files to show up in the main directory (myRepository) instead of where the source codes are (myRepository/myProgram) and be able to execute java Program while inside myRepository?

  • FlamesPuck12
    FlamesPuck12 about 13 years
    So there is no way to make it so that I can just type "java Program" and make it work from the main directory when the source codes are in a different directory?
  • Paŭlo Ebermann
    Paŭlo Ebermann about 13 years
    Apart from writing a new java implementation, no. You may think about using an IDE, where you can simply press a button (or hit a hotkey) to compile and run your code.
  • FlamesPuck12
    FlamesPuck12 about 13 years
    Nvm, I got it working using this method. I was hoping I could just set it up so that I could do java Program in the main repository directory but I guess this will have to do.