How to compile and run a Java program in command prompt?

Here is an example if you are going to use OpenJDK. This helps when it’s too slow to load a Java IDE to compile the source files (For example, on Raspberry Pi platform; I’ve tried Geany and Netbeans. It takes forever to load…).

  1. From Terminal install the open jdk
    sudo apt-get install openjdk-7-jdk
  2. Write program and save the file as filename.java
  3. Now to compile use this command from the terminal
    javac filename.java

    If everything work well you will notice a filename.class file is also created.

  4. To run your program you compiled use the below code in terminal:
    java filename

NOTE

You can use any text editor (like gedit) ,

replace the filename with watever name you want

you need to be on same directory as the “present working directory” (got by running pwd) while running the command from terminal.

Advertisements