How to compile a .java file on Ubuntu?

To compile the file, open your terminal and type

javac filename.java

To run the generated class file, use

java filename

But to do this you need to have the Java JDK installed in your computer. You can install it with the instructions in How do I install Java?.


OpenJDK works best for me. It's simple and I have never faced any problem with it. Just follow these simple steps:

  1. From Terminal install open jdk

    sudo apt-get install openjdk-7-jdk
    
  2. Write a java program and save the file as filename.java

  3. Now to compile use this command from the terminal

    javac filename.java
    

    If everything works well then a new "filename.class" file should be created.

  4. To run your program that you've just compiled type the command below 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.


If for example your file is my_file.java:

class MyClass
{
    public static void main(String[] args)
     {
       System.out.println("Hello World");
     }
}

You want to do:

javac my_file.java

and then

java MyClass # The name of the class, not file

However, it is a common convention to give classes and files the same name.

Tags:

Java

Compiling