Compile and Run Java Programs in One Click!

Here is how we can compile and run Java programs in one click. Yes, you heard it right and that is absolutely true. What about commands? Do i need to write them. Of course, you need them, but you don't need them to type always.

Creating a batch file lets you do this. In this post you'll learn how to compile all Java programs, wait till the output is seen, hide the echo as well!

Before we start, let us talk a bit about the batch files.
  1. They are the files which contains a set of commands that are executed in the command prompt one by one.
  2. They are saved with a .bat extension.
  3. Whenever you click on that file, those commands are executed one after the other.
So, it is clear that you need to write the two commands that compile and execute your program. They are javac and
java MyProgram
OK. That's it? Can we just include these two lines and save the batch file? Hmm, but you can't see the output, unless it is a GUI program. Because, the output is printed and the command prompt is closed. That's it. Now, is there a solution? Yes, here it is.

Pause batch file to display output

@echo off
java MyProgram

The pause command stops the command prompt from exiting.
The @echo off command doesn't display the path of the directory in the command prompt. For instance, if you are executing this in the folder E:\java then E:\java> is not visible. Just see it in practice for a clear understand.

Though there are any errors, then the second command is executed. The program will run depending upon the previous class file (if any). Otherwise, could not find or load main class MyProgram error will be displayed.
To prevent this, you can delete the previous class file and that command should be placed before.

Stop executing previous class file code [Use with caution]

@echo off
del MyProgram.class
java MyProgram

I recommend you to use this with caution, once the previous class file is deleted, you might not get back your code. Your program stays fine, but it is a modified version that contains errors.

One last tip, to compile all the classes, use javac *.java
@echo off
javac *.java
However, you cannot execute all programs at a time. You'll need to write one by one.

Writing and saving them?

  1. Write those commands in notepad and save them in the directory where your Java programs are present.
  2. Click on that batch file, every time you write it!
  3. To make your life more easy, just create a shortcut for that batch file on your desktop
and here we go, click it every time to compile and run!

If you like this post, please share it, it would be the highest price you could pay for this post.

Image credit:

Posted by at on

Tags: Miscellaneous, Tips,