Java running program from command line

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 :

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:

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; >>
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:

Читайте также:  Указать размер массива java

Command Explanation :

  • “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.
  • 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
  • It will run the program. her we have to again specify that where all the class files exist with the help of parameter “-classpath

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

Share this post

Comments

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

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

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

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

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

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

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

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.

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.

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

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

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 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();
>
>

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

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Â

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 🙁

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

[…] 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 […]

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

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);
>
>
>

Источник

Java: Program execution from Command Line and Eclipse with Arguments.

In the previous post First Java “Hello World” Program, you got some basic understanding for starting a Java Program. In this post, you will learn about to execute a Java Program from Eclipse and Commandline. Here consider both the case by passing with and without arguments to the main method().

Points to Remember

These are some points that need keep in mind while passing arguments from the eclipse or command line.

  • When you need to pass more than one argument. These values separated by spaces.
  • If passing an argument String value having space make sure to pass in the double quote (” “). For Example: “Saurabh Gupta”.
  • Always check for the length of main() method argument otherwise you may get ArrayIndexOutOfBoundException if trying to access index beyond passed arguments.

Execute Java Program from Eclipse without Arguments

When your program not required any argument to pass in main() methods follow these steps to execute a program.

For Example :

Output

  • Step 1: Go to the Java Class file “TestProgram”.java.
  • Step 2: Right-click on the file select option as “Run As” ->“Java Application”.
  • Step 3: You will see the output in the console tab.

Execute Java Program from Eclipse with Arguments

When your program required arguments to pass in the main() method follow these steps to execute a program.

For Example:

In this program, main() method required three arguments to print for “First Name “, “Last Name ” and “Full Name”.

Output

 Hello World ! Number of argument passed :3 First Name :Saurabh Last Name :Gupta Full Name :Saurabh Gupta 
  • Step 1: Go to the Java Class file “TestProgram”.java.
  • Step 2: Right-click on the file select option as “Run As” ->“Run Configuration”.
  • Step 3: You will get pop up, Go to the “Arguments” tab pass arguments in the “Program Arguments” section as mentioned in the below screen for this example.
  • Step 4: Click on the Run Button.
  • Step 3: You will see the output in the console tab.

Источник

Оцените статью