HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
1. Feel Free to ask and submit anything on and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.

java-compiler: How to compile and run java program by java code?

I want to compile a .java file by another java program. Please give me a sample program.

java x 211
compiler x 5
Posted On : 2014-11-18 12:26:33.0
profile Garima Gupta - Garima Gupta


You can use Runtime class's method to execute the command like javac, java, etc. For example:
Process pro = Runtime.getRuntime().exec(command);
Where command is the String type argument, its value may be like "javac", "java class_name"

Following is the working program to Compile and run another java file. Suppose we have a java file named and we need to compile and run this file. Its source code is like following:
public class Main {
public static void main(String[] args) {
System.out.println("This is Main class.");

And following is the java source code to compile and run the above file:

public class JavaCompiler {

private static void printLines(String name, InputStream ins) throws Exception {
String line = null;
BufferedReader in = new BufferedReader(
new InputStreamReader(ins));
while ((line = in.readLine()) != null) {
System.out.println(name + " " + line);

private static int runProcess(String command) throws Exception {
Process pro = Runtime.getRuntime().exec(command);
printLines(command + " stdout:", pro.getInputStream());
printLines(command + " stderr:", pro.getErrorStream());
return pro.exitValue();

public static void main(String[] args) {
try {
System.out.println("Compiling by javac");
int k = runProcess("javac");
if (k==0){
System.out.println("Compiled Successfully....");
System.out.println("Running by java Main....");
k=runProcess("java Main");
} catch (Exception e) {

Now you just have to compile and run only file by command prompt.
Java Compiler Output

Download this example- Click Here

Posted On : 2014-11-18 12:58:41
Satisfied : 1 Yes  0 No
profile Rishi Kumar - Rishi Kumar
Reply This Thread

Post Answer
Please Login First to Post Answer: Login login with facebook -