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

Posted

in

by

Tags:


Related Posts

Comments

40 responses to “Compile and run Java program in package from command line”

  1. […] Create Executable jar file of classes in package Posted by Jitendra Zaa on April 14th, 2011 For the source code, please refer this article. […]

  2. fazhil Avatar
    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

  3. praveen Avatar
    praveen

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

  4. sampath Avatar

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

  5. raj Avatar
    raj

    hard to understand….

  6. Maddy Avatar
    Maddy

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

    1.  Avatar
      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

      1. Maddy Avatar
        Maddy

        Thanks…it’s working 

  7. Rachana Gandhi Avatar

    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

    1.  Avatar
      Anonymous

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

      Regards,
      Jitendra Zaa

      1. Lourthu Avatar
        Lourthu

        yes its working by the way you said..but what should i have to do the class files are in the same package where he classes are stored. bcz i’m having two classes with in com.example.payroll. the first class employee.java has compiled successfully but when i try to compile Test.java which has initialization of an object employee class shows cannot find symbol error i don’t know what is the reason here.

  8. Itswatisoni06 Avatar
    Itswatisoni06

    please give some simple programe of packages

  9. Khan Rihan12 Avatar
    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.

    1. JitendraZaa Avatar
      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

  10. Kdharmveer13 Avatar
    Kdharmveer13

    package is hard to run help everyone who wants help thank

    1. JitendraZaa Avatar
      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

  11. Somasekharkote Avatar
    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();
    }
    }

    1. JitendraZaa Avatar
      JitendraZaa

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

  12. Ashish Sharma Avatar
    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 

    1. JitendraZaa Avatar
      JitendraZaa

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

      1. Ashish Sharma Avatar
        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 🙁

    2. don Avatar
      don

      hmmmm okay

  13. Manish Patel Avatar
    Manish Patel

    Thanks. It works… 🙂

  14. mountainb Avatar

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

  15. […] it a matter of guesswork. Originally Posted by JavaEnthusiast Could you please explain…] Compile and run Java program in package from command line | Shiva Blog Java Practices -> Command line operations Cheers! Z Reply With […]

  16. ramesh Avatar
    ramesh

    thx a lot for this post, thx once again,

  17. santo borg Avatar
    santo borg

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

  18. Dipak Kumar Avatar
    Dipak Kumar

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

  19. Shraddha Avatar
    Shraddha

    package jp.co.global;

    this is my package….. how shud i compile n run it?

    my classname is Main

    1. shraddha Avatar
      shraddha

      this is nt d pkg created by me… m preparing 4 a cmpny n it hs told 2 use dis pkg in d code

  20. nickname Avatar
    nickname

    thanks

  21. winnersravi meena Avatar
    winnersravi meena

    if i change the package name of Start.java then how to run it

  22. Aalsi Procrastinatior Avatar
    Aalsi Procrastinatior

    You are a life saver man! Thanks a ton 🙂

  23. Govindarajan D Avatar
    Govindarajan D

    Thanks 🙂

  24. sahana Avatar
    sahana

    sir how to run this
    import java.net.*;
    import java.io.*;
    import java.sql.*;
    class trainserver
    {
    public static void main(String args[])
    {
    String Query;
    ResultSet rs = null;
    String msg;
    int pnr = 0,trainnum=0;
    String from = new String();
    String to = new String();
    String date = new String();
    String name = new String();
    try
    {
    ServerSocket ser=new ServerSocket(8000);
    System.out.println(“Server Started…”);
    Socket soc=null;
    soc=ser.accept();
    System.out.println(“Received Connection: “+soc.getInetAddress().getHostAddress());
    DataOutputStream out=new DataOutputStream(soc.getOutputStream());
    BufferedReader in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
    try{
    Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
    Connection conn=DriverManager.getConnection(“jdbc:odbc:mydb”,”scott”,”tiger”);
    Statement stmt=conn.createStatement();
    msg = in.readLine();
    pnr = Integer.parseInt(msg);
    Query = “Select * from train where pnrno = “+pnr;
    rs = stmt.executeQuery(Query);
    if(rs.next())
    {
    pnr = Integer.parseInt(rs.getString(1));
    from = rs.getString(2);
    to = rs.getString(3);
    date = rs.getString(4);
    name = rs.getString(5);
    trainnum=Integer.parseInt(rs.getString(6));
    }
    else
    {
    System.out.println(“invalid PNRNO”);
    }
    }
    catch(SQLException e)
    {
    System.out.println(“Error Caught: “+e);
    }
    out.writeBytes(“”.valueOf(pnr));
    out.write(10);
    out.writeBytes(from);
    out.write(10);
    out.writeBytes(to);
    out.write(10);
    out.writeBytes(date);
    out.write(10);
    out.writeBytes(name);
    out.write(10);
    out.writeBytes(“”.valueOf(trainnum));
    out.write(10);
    soc.close();
    }
    catch(Exception e)
    {
    System.out.println(“Error Caught: “+e);
    }
    }
    }
    //Client side

    class traindbclient
    {
    public static void main(String args[])
    {
    Socket objclient= null;
    BufferedReader br = null,in = null;
    DataOutputStream out = null;
    int pnr = 0;
    try
    {
    objclient = new Socket(“Localhost”,8000);
    in = new BufferedReader(new InputStreamReader(objclient.getInputStream()));
    br = new BufferedReader(new InputStreamReader(System.in));
    out = new DataOutputStream(objclient.getOutputStream());
    System.out.println(“Enter the PNR NO: “);
    pnr = Integer.parseInt(br.readLine());
    out.flush();
    out.writeBytes(“”.valueOf(pnr));
    out.write(10);
    System.out.println(“PNRNo: “+in.readLine());
    System.out.println(“SOURCE : “+in.readLine());
    System.out.println(“DESTINATION: “+in.readLine());
    System.out.println(“JOURNEY DATE: “+in.readLine());
    System.out.println(“CUSTOMER NAME: “+in.readLine());
    System.out.println(“TRAIN NO: “+in.readLine());
    objclient.close();
    }
    catch(Exception e)
    {
    System.out.println(“Error Caught: “+e);
    }
    }
    }

  25. sahana Avatar
    sahana

    please give me solution sir

  26. Ngo Alalibo Avatar
    Ngo Alalibo

    thank you. Had been trying to do this for several hours until I read your post. You’re right here “…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…. “

    1. subbaraman ramaswamy Avatar

      How to download the java compiler with jdk and jre having same versions and to run java programs in command line by setting the path?

  27. Michael Lueck Avatar
    Michael Lueck

    Thank you for the hint I needed this evening to get “Hello World!” to run built with Eclipse. The Eclipse tutorials all stated to “best practice” put your Java source within a Package. They never explained how that would make things more complicated to run the resulting Java program.

    In my case, I needed to have the current directory be just the bin directory… not where the .class file actually is.
    Then execute command line: java com.g2.ExecJar.Start Per your example.

    Now I can get a good night’s rest, and not have my mind thinking of things to try to get the Eclipse produced .class file to actually run with Java from the command line. Phew!!

  28. EPAPHRAS Avatar

    Thanks a lot to ALL TEAM, this tutorial help me to understand all I want.

Leave a Reply to JitendraZaaCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading