I have been using an IDE but now, in order to prepare my 1Z0-803 exam, I need to run and compile from the command line. The problem is that I have multiple packages and I have tried to find the answer but nothing has worked so far.
So I have :
package com.oca.tutorial;
import com.oca.tutorial.planets.Earth;
import com.oca.tutorial.planets.Mars;
import com.oca.tutorial.planets.Venus;
public class GreetingUniverse {
public static void main(String[] args) {
System.out.println("greetings universe");
new Earth();
new Mars();
new Venus();
}
}
Venus class:
package com.oca.tutorial.planets;
public class Venus {
public Venus() {
System.out.println("Hello from Venus");
}
}
Mars class
package com.oca.tutorial.planets;
public class Mars {
public Mars (){
System.out.println("Hello from Mars");
}
}
And my Earth class
package com.oca.tutorial.planets;
public class Earth {
public Earth (){
System.out.println("Hello from earth");
}
}
Command Line + error
Expected output:
greetings universe
Hello from earth
Hello from Mars
Hello from Venus
Fiel Structure for planets :
C:\OCA\com\oca\tutorial\planets
Fiel Structure for main GreetingUniverse :
C:\OCA\GreetingUniverse
error message from command prompt:
Note that you declare packages for each of your classes.
GreetingUniverse
is in thecom.oca.tutorial
package andVenus
,Mars
, andEarth
are in thecom.oca.tutorial.planets
package. Java requires that a .java file is located in a directory which mirrors its package name. For example,GreetingUniverse.java
needs to be in a subdirectory calledcom\oca\tutorial
. This subdirectory can be in theOCA
directory which you are currently using to compile from.If you still get similar errors after moving your .java files to the correct directories, try including all the .java files for every class in the same command-line. It has been a long time since I compiled large-ish projects from the command-line. From what I remember this shouldn't be necessary, but it is certainly worth a try.
Edit:
To clarify, this is how your directory structure should be set up:
Now run the following command:
First you can cd to the base directory, where com/ is located. Then,
javac -d bin com\oca\tutorial\*.java com\oca\tutorial\planets\*.java
Edit: As the above posters say (and discovered), your file structure is wrong. If you have class GreetingUniverse in package
com.oca.tutorial
, then file path should be com\oca\tutorial\GreetingUniverse.java.Make sure that all files can be found by the compiler. Go to the directory containing the
com
folder and use:or simply
with this file structure
You need to be located in
C:\OCA
when doing the compilation.