Using javac and java commands to compile and launch java programs

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Here we are going to learn how to compile java classes and launch them when they are defined in some classes using javac and java commands.
Suppose we have two java files. Parent.java and Child.java defined in packages packageOne and packageTwo respectively.
Child extends Parent and tries to access the protected member of Parent class.

The structure for the same is.

C:\sources\packageOne\Parent.java
C:\sources\packageTwo\Child.java

And the sources files are

Child class is

Now let us compile these two sources files. First Parent.java. Navigate to packageOne directory and compile as follows.

It will create Parent.class. So Simple, nice and clean now we need to compile Child.java. Should we follow the same procedure as above? Let us try for that. Navigate to packageTwo directory and run javac as follows. What do we get?

Parent.java compiled successfully but Child didn’t. Why is that? Are we using the command properly? Let us try compiling again, now using the package structure for the Child class.Navigate to sources directory and run

Now it compiles successfully and generates class file for the same.
Now we have to run Child class. It extends Parent class so it needs to know where exactly Parent class is located. It is in the sources directory.

Note that even though it looks like Parent class is located in packageTwo directory, its actually the package name which is represented by a folder. Actually a class is identified by its fully qualified name which is made up of its package name and class name. So the actual name of class Parent is packageOne.Parent and the name of Child class is packageTwo.Child.

Let us go through quickly

  1. Navigate to sources directory
  2. Compile Parent class first as it is required for Child class using command javac packageOne/Parent.java.
  3. Then compile Child class using javac -classpath . packageTwo/Child.java. Here -classpath is the option to tell javac command from where to pick the classes required for Child.java and . is the current directory which is our classpath i.e. sources.
  4. After compilation is successful, run Child class using java packageTwo.Child. Here we are using fully qualified name for Child.

javacAndJavaCommandLine

Ideally you should always compile and launch java classes from the room of the directory structure. package names in the java files are directory structures. While compiling they are treated as java files so directory structure is used while compiling e.g. packageOne/Parent.java . But when the classes are compiled, then class files are identified using the package names. So use the fully qualified names from the root directory i.e. the location from where package structure starts. In our example, sources is the directory and packageOne and packageTwo are packages. So the classes should be referred as packageOne.Parent and packageTwo.Child.

Share Button

24 comments for “Using javac and java commands to compile and launch java programs

  1. Alan
    December 20, 2013 at 2:58 pm

    Good read and thanks for answering my questions! 🙂

  2. Sumit
    November 16, 2014 at 2:03 am

    Why does the java command needs a directory structure (javac PackageOne/Parent.java) while the java command needs a package structure(java packageTwo.Child). Should it not be consistent?

    • November 20, 2014 at 10:50 pm

      because we are compiling files and when they are compiled they become java classes. packageTwo.Child is fully qualified name for the class in which packageTwo is a package. Operating system shows package as folders.

      • Michael McKenzie
        May 26, 2015 at 5:21 am

        This works in eclipse. Wont compile on command line – says imported package does not exist:

        Have two classes in two different packages (no inheritance)
        class A SpecialDelivery – PKG = com.mgm2.specialdelivery
        – Class B (UrgentMessage) has main() imports com.mgm2.specialdelivery.SpecialDelivery

        c:\ src\com\mgm2 – has both specialdelivery and urgentmessage package paths -compile SpecialDelivery.java OK

        Try to compile UrgentMessage from directory with both specialdelivery and urgentmessa pat h names so they are visible and get package specialdelivery does not exist.

        To compile UrgentMessage.java use command
        c:\\src\com\mgm2 javac urgentmessage/UrgentMessage.java then it doesn’t reconize specialdelviery package even though I am compiling from the directory with both of them there.

        Thanks for your help

  3. Kalidoss
    November 27, 2014 at 12:26 pm

    Sir i need java code to create and print all the JFrame or JInternaframe Components
    in printer.ex, generate invoice,bill and print in printer

  4. Raaj Kanchan
    May 30, 2015 at 8:11 pm

    What if both the Parent and Child exists in the same packageOne.

    • harsh
      June 23, 2015 at 5:37 pm

      If both the files is on the same package the then simply type the following…

      Javac *.java

  5. Raaj Kanchan
    May 30, 2015 at 8:14 pm

    What if both the Parent class and Child class exists in the same packageOne. Do I have to compile the Child class using
    C:\sources> javac packageOne/Child.java

    • June 1, 2015 at 9:25 am

      For compiling you can directly navigate to directory and compile using javac

      • Raaj Kanchan
        June 1, 2015 at 1:58 pm

        Yeah, It worked, Thanks a lot…

  6. vikrant
    June 25, 2015 at 4:40 pm

    Hi,

    pls guide me how to compile whole package containing multiple folders of java files.

    Thanks in advance.

    • June 26, 2015 at 9:11 am

      you will have to give path for every diretory and then *.java for example. java dir1/dir2/*.java. But You should really use some build tools like maven, gradle or IDE like eclipse for complex projects.

      • October 23, 2015 at 5:13 pm

        thank u very much!!!!!

    • basavaraj
      July 24, 2015 at 7:28 pm

      put every java files path in one text file and name it whatever you want, but that file has to be in the project root folder.
      Ex: lets say you have created listoffiles.txt in project root folder. put the list of java file name in that text file(com/program/myprogram/Myapp.java com/program/myprogram/Myapp.java….) by giving space to each file, once you have done that

      type the command

      javac @listoffiles.txt

      it will take all the path from txt file and compiles it.

      hope this helps.

  7. kannan
    July 24, 2015 at 6:53 pm

    i’m compiling and running java program from command prompt without any error by using the keywords
    “cd file directory”
    “setpath=java installed folder”
    “javac filename”
    “java classname”
    but in rare cases like importing packages just like “import Shape.*;” and
    “import JavaDrawFrame.*;” i’m getting error says “error: package Shape does not exist”.kindly help me…

  8. August 24, 2015 at 3:43 pm

    Dear Java enthusiasts,

    Do not forget to to know about Java -d and besides java -cp if you want to know about java command line tools like javac, java, javap etc.

    note: If the -d option is specified, however, the specified directory is treated as the root of the class hierarchy, and .class files are
    placed in this directory and/or appropriate subdirectory below according to the package name. For more details please refer official java documentation.

  9. Sonali
    April 12, 2016 at 6:39 pm

    I create three classes ..Protection.java,Derived.java (that extends Protection) and SamePackage.java(that dont extend protection but use protectd variables of it)(all in same package p1).
    Now I create two more classes in package p2 named file1.java that extends protection class and file2.java.
    How i compile all these files? (Protection.java and derived.java are compiled successfully).

  10. Deekshith
    September 11, 2016 at 12:24 am

    Hey I created a package “myPack” and a class “A” in it, now if I want to run class and get the out put how should I do it in command prompt

    package myPack;
    public class A
    {
    public static void main(String[] args)
    {
    System.out.println(“This is package”);
    }
    }

  11. Divya Balasubramanian
    September 16, 2016 at 12:08 pm

    Awesome! clarified some of my doubts. Thanks.

  12. Muad'Dib
    October 7, 2016 at 6:56 am

    I have a very similar problem using Java 8 from Oracle on a Mac run from the bash shell:

    My java class Source is defined as follows…

    package Users.me.project.java.jp1;

    public class Source {
    public static void main(String args[]) {
    System.out.println(“Jambo!”);
    }
    }

    From my user root directory “/Users/me/” this command…

    javac -cp “/Users/me/project/java/jp1/” “Source.java”

    …successfully generates this file…

    /Users/me/project/java/jp1/Source.class

    …but this command…

    java Users.me.project.java.jp1.Source

    …generates this message…

    Error: Could not find or load main class Users.me.project.java.jp1.Source

    Error: Could not find or load main class

    Moving to the project directory…

    cd project/java/jp1

    …and running from there…

    java Users.me.project.java.jp1.Source

    …generates the same message…

    Error: Could not find or load main class Users.me.project.java.jp1.Source

    Similarly,…

    java Source

    …generates roughly the same message…

    Error: Could not find or load main classSource

    Clearly, I have missed something fundamental or something fundamental is missing from the text book I’m using and from every tutorial on the interweb that I have looked at today. That, or Java doesn’t work as advertised. Any ideas?

    • October 10, 2016 at 9:08 am

      While compiling you are using direct file path name which is coming from root directory. It is quite correct as you are simply specifying file path. While launching a java program. You should invoke it from the directory from where your package structure starts. So if your package is Users.me.project.java.jp1 then your command should be be java Users.me.project.java.jp1.Source.

      Please try to run java command where your Users directory is present. So just go to parent directory of Users and run java Users.me.project.java.jp1.Source

  13. Pragun
    November 19, 2016 at 11:54 pm

    Hi Prasad,

    Here is what I found out while playing with the above code and compiling it (not executing/running).So, I had two folders packageOne and packageTwo, both of which contained Parent.java and Child.java respectively. I have deliberately omitted one line in both java files which specifies package. So, my Child.java does not contain ‘package packageOne;’ and Parent.java does not contain ‘package packageTwo;’. I executed following commands inside root folder(folder which contained packageOne and packageTwo):

    Case 1:
    >javac packageOne/Parent.java
    (Compiled successfully)

    >javac packageTwo/Child.java
    >Error: packageTwo\Child.java:1: error: cannot access Parent
    >import packageOne.Parent;
    > ^
    > bad class file: .\packageOne\Parent.class
    > class file contains wrong class: Parent
    > Please remove or make sure it appears in the correct subdirectory of the classpath.

    Case 2:
    >javac PackageTwo/Child.java
    >Error: packageTwo\Child.java:1: error: cannot access Parent
    >import packageOne.Parent;
    > ^
    > bad source file: .\packageOne\Parent.java
    > file does not contain class packageOne.Parent
    > Please remove or make sure it appears in the correct subdirectory of the sourcepath.

    Now, Case 2 is very obvious since we are have trying to compile Child.java without/before compiling Parent.java.

    What is interesting is Case 1.
    Here I have successfully compiled Parent.java but I am unable to compile Child.java. I also tried ‘javac -classpath . packageTwo/Child.java’ so as to tell Java to look for classes in root folder but in vain as I got the same error. Even though Child.java contains line ‘import packageOne.Parent;’, this scenario makes me think that java will not automatically infer from line ‘import packageOne.Parent;’ that Parent.class is inside packageOne folder. We have to explicitly write ‘package packageOne’ in Parent.java. And, yes when I did that, Child.java compiled.

    But I still have not written ‘package packageOne;’ in Child.java.
    Does it matter when we have both the Java files compiled? Yes, it does. This is what happened when I tried to execute this command ‘java packageTwo/Child’ or ‘java packageTwo.Child’
    >Error: Could not find or load main class packageTwo.Child

    Finally when I added ‘package packageOne;’ in Child.java as well, recompiled and executed it ran fine.

  14. Djordje Lukic
    March 8, 2017 at 12:14 am

    Thank you sir,this really helped me immensely.

  15. May 18, 2017 at 6:51 pm

    Nice article about commands like java and javac for running any java programs.
    keep posting for us
    thank you sir.

Leave a Reply

Your email address will not be published. Required fields are marked *