Compile and run Java program in package from command line

The topic is very easy and i am sure that lots of java programmer already know how to compile java program existing in package. However there are users who frequently works on eclipse, netbeans or any other IDE and don’t know that how the program actually works behind the IDE. So this article basically emphasizes on basics of Java Compilation.

Consider following directory structure :

Java Directory structure

Java Directory structure

Our java files will be in “src” folder. I want all the class files in folder “classes” and currently i am in folder “Exec Jar“.

Consider below Java Files:

Person.java

package com.g2.ExecJar;

public class Person {
	private String name;
	private int age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
}

Start.java

package com.g2.ExecJar;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Start {

	public static void main(String[] args) {

		try {
			InputStreamReader io = new InputStreamReader( System.in );
			BufferedReader read = new BufferedReader(io);

			System.out.println("Enter Name");
			Person p = new Person();
			p.setName(read.readLine());

			System.out.println("Enter Age");
			p.setAge(Integer.parseInt( read.readLine()) );

			System.out.println( "-------- You have Eneterd --------- " );
			System.out.println("Name : " + p.getName());
			System.out.println("Age : " + p.getAge());

			System.out.println( "---------- Progarm run by executable jar ------------ " );

		} catch (IOException e) {
			e.printStackTrace();
		} catch (NumberFormatException e) {
			System.out.println("Age entered is not in correct format");
		}
	}
}

Run below steps to compile and run java programs from command line:

Compile and run Java Program in Package from Command Line

Compile and run Java Program in Package from Command Line

Command Explanation :

Line 1 :

  • “javac” is the java compiler available in bin folder of the jdk.
  • -d” stands for the “directory“. it explains compiler that where the class files should be created.
  • Last argument is the Complete path, where the java file exists.

Line 2 :

  • in line 2, you have noted one extra parameter “-classpath“. As class “Start” depends on class “Person” and its class file is not in the same directory.  Therefore we need to explicitly tell compiler that where it can find required class files.
  • To include more than one classpath use semicolon “;”.  Example:  -classpath path1;path2;path3

Line 3 :

  • It will run the program. her we have to again specify that where all the class files exist with the help of parameter “-classpath

The complete set of argument supported by the java compiler can be found on the Oracle site.

Next article, How to create executable jar file for packages in java

This entry was posted in JAVA and tagged on by .

About Jitendra

Sr. Consultant at Cognizant Technology Solutions. Have more than 7 years of experience in technologies and frameworks like Salesforce, Node.Js, JAVA, PHP, JSP, Struts, Hibernate, C#, ASP.NET, SQL Server. Also many javaScript libraries like AngularJs, JQuery, JQuery Mobile, BootStrap. Connect : Linked In

Related posts

  • Pingback: Create Executable jar file of classes in package | Shiva Blog

  • fazhil

    if have another directory to execute the java program
    to compile the program
    c:/>javac -cp d:sub;. use.java
    to execute the program
    c:/>java -cp d:sub;. use

  • praveen

    hey can u clearly show us d command dt what’s d syntax to compile a program which use package….??

  • http://www.shivasoft.in sampath

    sorry we didnt understood ;;;;eplain clear whatever u want ………..

  • raj

    hard to understand….

  • Maddy

    Option -d works if the directory structure is already there.What if the directory structure doesn’t exist from before?

    • Anonymous

      Not Complete Directory structure. You just need to give the root path for the “.class” files. Remaining folders will be automatically created as per package structure.

      Regards,
      Jitendra Zaa

      • Maddy

        Thanks…it’s working 

  • http://twitter.com/r_m_gandhi Rachana Gandhi

    can you please explain little more deeply…??? i can’t understand….can’t you give any example which uses package and importing a user defined package…???

    -Thanks

    • Anonymous

      Hi Rachana,
      Please follow the steps as per article. I have included the screens also. It worked for everyone.

      Regards,
      Jitendra Zaa

  • Itswatisoni06

    please give some simple programe of packages

  • Khan Rihan12

    sir i m unable to compile and run java package in jdk1.77. so pls tell me sir how can compile and run packages in java.

    • JitendraZaa

      Hi Rihan,
      Please follow the exact steps with same folder name, if you still face any problem than attach your screen shot showing error. i will surely guide you.

      Thanks,
      Jitendra Zaa

  • Kdharmveer13

    package is hard to run help everyone who wants help thank

    • JitendraZaa

      I know its hard to run, thats why i have provided article. I have provided screen shots with step by step description. Just follow the same folder names and instructions. If you get any error then reply with full description.
      Regards,
      Jitendra Zaa

  • Somasekharkote

    sir how to run this program plssssssssssssss

    //multiplication.java
    package mp;
    public class multiplication
    {
    int n;
    public multiplication(int n)
    {
    this.n=n;
    }
    public void table()
    {
    if(n<=0)
    {
    System.out.println(n+"invalid input");
    }
    else
    {
    for (int i=1;i<=10 ;i++ )
    {
    System.out.println(n+"*"+i+"="+(n*i));
    }
    }
    }
    }

    //Satyauser.java
    import mp.multiplication;
    class  Satyauser
    {
    public static void main(String[] args) 
    {
    int n = Integer.parseInt(args[0]);
    multiplication mo=new multiplication(n);
    mo.table();
    }
    }

    • JitendraZaa

      Hi Somasekharkote,It will need command line argument which will be converted as number and print the multiplication table.

  • Ashish Sharma

    Thank you for the good article, I was able to proceed further using this article, but I have getting this error (PFA screenshot)

    I have my java file stored in                                    C:UsersAshi’sworkspaceJavaPracticeMyPack 
    and I have my java executable files stored at            C:Program FilesJavajdk1.7.0_02bin 

    • JitendraZaa

      Hi Add the path upto java/bin in “Classpath” and run the program from base package

      • Ashish Sharma

        Thank you for the reply Sir, but I did not understand what you mean by the above statement. Are you intending on going to my executable files folder and then using the classpath flag along with javac command? Really confused here :(

    • don

      hmmmm okay

  • Manish Patel

    Thanks. It works… :-)

  • http://pulse.yahoo.com/_UP36WYO6AON6Z65KROJWLQVSOE mountainb

    Thanks Ran on Ubuntu 12.04 just as is. I did have to include all the directories to the source file.
    b

  • Pingback: Trouble running a java file from the windows command prompt.

  • ramesh

    thx a lot for this post, thx once again,

  • santo borg

    if i can write the both files (package & main class file) in one program then how to run this program.

  • Dipak Kumar

    It’s not working sir , I did the above step as you mention , It creating lot of confusion