How to Compile Java Source within Java Program

By Angsuman Chakraborty, Gaea News Network
Thursday, March 26, 2009

This small trick will tell you how you can compile a java source file from another java file on the go. You do not need to run it on a different page and compile it there and then get back to this program. This will be immensely helpful for a program that has some dynamic segments of codes which need to be compiled here within. Basically what we are gonna do is  we will use getSystemJavaCompiler() method in the ToolProvider class  that returns an object of some class that implements JavaCompiler. 

1. The implementation needs  tools.jar file usually available in the <JDK60_INSTALLATION_DIR>libtools.jar. So you need to give the proper directory path in the class path so that we can use import*
Or you can use

cp /usr/java/jdk<version>/lib/tools.jar /usr/java/jdk<installation directory>/jre/lib/ext/

this command above to change it from terminal.

2. Now to compile that program from within another Java file, here is the code snippet you need to use

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if(, null, null, fileName + “.java”) != 0) {
// Error message

And you are done.


March 30, 2010: 4:17 am

I want to compile a java program ,location of which is C:\ass\ I compile the program from other drives such as D:\ or E:\ or from any other location like D:\surachit\aal\sd
pls mail me

anil kanhangad
February 15, 2010: 11:46 pm

i am able to run first java command succesfully (javac0.but not able to run the second one(ie java)..what is the peroblem?

August 4, 2009: 3:39 pm

Fandoo Code… And its work 2.

will not be displayed