AI Hints
Home›Java Tutorial›Installing the JDK, Trying Java in JShell and Your First Program
Java · Lesson 6 of 120

Your First Program

Main.java.

⏱ 2 min read▶ Video at 6:49🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

A Java program lives in a text file, ending in dot java. You compile it, then run it, as many times as you like.

  • A .java file
  • Compile it
  • Run it

Main.java

Here is our first program, saved as Main dot java. The file name must match the class name, Main, with a capital M. The two print lines are the part that does the work. Run it. Java greets us, and shows forty two.

Main.javajava
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
        System.out.println("Java can do maths: " + 6 * 7);
    }
}
Output
Hello, Java!
Java can do maths: 42

Compile, then run

In the terminal, ls shows our file. Javac, then the file name, compiles it. Now ls shows a new file, Main dot class. That's the bytecode. And java, then the class name, Main, runs it. Notice there's no dot class on the end.

Terminal
ls
Main.java
javac Main.java
ls
Main.class
Main.java
java Main
Hello, Java!
Java can do maths: 42
File used: Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
        System.out.println("Java can do maths: " + 6 * 7);
    }
}

A shortcut

Since Java eleven, you can skip the compile step, for a single file. Type java, then the file name, with dot java on the end. Java compiles it in memory, and runs it straight away. In this course, the editor runs code this way.

keyvalue
Two stepsjavac Main.java, java Main
One stepjava Main.java
Works fora single file
This courseuses one step

Summary

Save your code in Main dot java, compile with javac, and run with java. Or use java Main dot java, in one step. Next, what all those words around our code mean.

Key takeaways
  • File name = class name
  • javac, then java
  • java Main.java
Next up: The main Method — where every program starts