Java Get Started
A Java program is written in a text file that ends with .java. Before it can run, the Java compiler (javac) turns it into bytecode, a compact form stored in .class files. Then the Java virtual machine (java) runs the bytecode. The same bytecode runs on Windows, macOS, Linux and phones: that is the famous Java promise, "write once, run anywhere".
In our online editor you do not need to install anything. Press Run and the editor compiles your program with javac and runs it with java, both inside your browser.
Your first program, line by line
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
System.out.println("I am learning Java.");
}
}Hello, World! I am learning Java.
public class Mainstarts a class calledMain. In Java all code lives inside classes. The file must be calledMain.java, the same name as the public class.- The curly brackets
{and}mark where the class starts and ends. public static void main(String[] args)is the main method. When you run the program, Java starts here. Every word has a meaning that later topics explain; for now, copy it exactly.System.out.println(...)prints a line of text. The text is written between double quotes.- Each statement ends with a semicolon
;.
The two println statements run from top to bottom, so the output has two lines in that order.
Compiling and running in the terminal
The editor also has a real terminal. These are the two commands that the Run button uses:
javac Main.java java Main
The first command creates Main.class. The second runs it; notice that you give the class name, Main, not the file name. Since Java 11 you can also run a single file directly with java Main.java: Java compiles it in memory and runs it at once.
When something is wrong
If your code has a mistake, javac refuses to create the class file and prints the line and the problem instead. Here the closing quote is missing:
public class Main {
public static void main(String[] args) {
System.out.println("Hello);
}
}Main.java:3: error: unclosed string literal
Read the message from the top: the file name, the line number, and a short description. Fix that line, and run again. You will learn more about reading errors in the Errors and Debugging topic at the end of this tutorial.
Practice exercises
- Write a program that prints three lines: your name, your age and your favourite food.
- Rename the class from
MaintoHellowithout renaming the file, run it and read the error. Change it back. - Open the terminal, type
javac Main.javaand thenjava Mainyourself.