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:
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:
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
Leave a Reply to ShraddhaCancel reply