Monday, 17 September 2012

How to compile and run a java file command prompt.

How to compile and run a java file command prompt.? 
What is PATH? What is CLASSPATH?


Compiling:
Create a file LearnSoftOnline.java .



The above program just prints a message on the console.
Place this file anywhere in the local system. Let us say, we place the file in E:/
Let’s assume Java is installed in the location C:\Program Files\Java\jdk1.6.0_33

1)    Open the command prompt and go to the location C:\Program Files\Java\jdk1.6.0_33\bin

2)    Type in java and press enter. You will get the below output. This is just to test that the java command is working fine.


3) TThe java compiler gets invoked by the javac.exe file.  If we want to compile any file, execute the javac command against the file name

 Ex: javac E:/LearnSoftOnline.java and press enter.


Please check the E:/ now. You will find the compiled file with a ‘.class’ extension (Ex: LearnSoftOnline.class)
Executing:
4)    The java files are executed using the java command against the file name (without extension)
Ex: java LearnSoftOnline 


We got this exception because the java command is searching for ‘LearnSoftOnline.class’ file in the current directory (C:\Program Files\Java\jdk1.6.0_33\bin), where that java executable file is present.
So, we need to tell the java executable file about the location of our class file.In the present case, our class file is in the location E:\LearnSoftOnline.class
This path where the class files exists is called the classpath.So when running the java command, we need to tell the java command where our class files are presen by setting the classpath.
The class path from the command prompt can be specified by ‘–cp’.  As our class file is present in the E:/ we need to specify the classpath as -cp E:/
So the command for executing the java class will be
C:\Program Files\Java\jdk1.6.0_33\bin>java -cp E:/ LearnSoftOnline



Once it is executed, we can see the message is printed on the console.

So, every time you want to run or compile a java file, we have to go to the directory where the java executable are present (Ex: In this case, C:\Program Files\Java\jdk1.6.0_33\bin ) and then execute the java and javac commands.
To avoid this, we can tell our machine that java is installed in C:\Program Files\Java\jdk1.6.0_33\bin . This is done by setting the path variable.
Once we add the path ‘C:\Program Files\Java\jdk1.6.0_33\bin ‘ to the PATH environment variable, we can use the java and javac commands irrespective of the current directory location.

Before setting the PATH variable:

After setting the PATH variable:

We can execute and compile the from any directory with out mentioning the java installation directory  




   
If we don’t want to mention the classpath everytime we run the java command, we add the path “E:/” to the CLASSPATH environment variable
Once you add the ‘E:/’ to CLASSPATH, the program can be executed as 





No comments:

Post a Comment