Sublime Text 2 is my Favorite text editor for coding. You also like after using this awesome and light weight editor. In this article we are discussing about Compile and run java programs with Sublime Text 2.

Step #1 – Set Java PATH variable
This is the first and basic step to compile and run java programs because it helps to find required files when you run or compile program like java, javac, etc

Steps to set PATH variable in Windows.

  1. Right click on My Computer
  2. Select Properties
  3. Go to Advanced system settings
  4. Find button Environment Variables… and click
  5. Go to System variables and find Path variable
  6. Paste jdk bin directory path in value filed in last

for example if your jdk bin path is C:\Program Files\Java\jdk1.6.0_17\bin paste it like in below image.

Set java path in windows

Set java path in windows

Steps to set PATH variable in Ubuntu
1. Go to File System > etc
2. Open environment file with admin(root) permissions

Sudo gedit /etc/environment

3. Paste jdk bin directory path in last before ” and save file;
4. Log off system to take effect changes.

Step #2. Create Batch or Bash Shell script file
To Compile and run java program create a batch or shell file

For Windows
Open text editor and save file as runJava.bat after pasting below code

cd %~dp1
ECHO Compiling %~nx1.......
IF EXIST %~n1.class (
DEL %~n1.class
javac %~nx1
IF EXIST %~n1.class (
ECHO -----------OUTPUT-----------
java %~n1

Copy this file to jdk bin directory.

For Ubuntu
Open text editor and save file as after pasting below code

[ -f "$1.class" ] && rm $1.class
for file in $
echo "Compiling $file........"
javac $file
if [ -f "$1.class" ]
echo "-----------OUTPUT-----------"
java $1
echo " "

Note: If you want to Compile all programs in directory replace $ with *.java in second line

Copy or Move this file to jdk bin directory using below command

Sudo mv /usr/lib/jvm/jdk1.6.0_17/bin

Above command used as Sudo mv SourcePath DestinationPath
After Moving file to jdk bin set its permission 755 by right clicking on file and select permission tab and check bottom check box to make it auto executable file.

Step #3 – Changes in Javac.sublime-build
To set these batch or shell scripts in Build system of sublime text 2 follow below instructions

  1. Open Sublime package directory using Preferences > Browse Packages..
  2. Go to Java Folder
  3. Open JavaC.sublime-build and replace line
"cmd": ["javac", "$file"],

in Windows with

"cmd": ["runJava.bat", "$file"],

in Ubuntu with

"cmd": ["", "$file_base_name"],

Step #4 – Now write programs and Run using CTRL + B

Build and Run Java Programs

Build and Run Java Programs