Your First Java Program
Meet the main method that starts everything
Every Java program needs a starting point, a single spot where the computer begins running your instructions. In Java, that starting point is called the main method.
Before we get to main, there is one rule to know: every bit of Java code lives inside a class. Think of a class as a container that holds your program. We will talk much more about classes later in this course, but for now just know that Java expects one.
The smallest complete Java program
Here is what a very small, complete Java program looks like:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
Let's slow down and look at each piece.
public class HelloWorldnames the container for our code. The name must match the file name, so this would be saved as HelloWorld.java.public static void main(String[] args)is the main method. Java always looks for exactly this line to know where to start.- The curly braces
{ }mark the beginning and end of a block of code. System.out.println("Hello, world!");is the actual instruction. We will look at this closely in the next lesson.
You do not need to memorize this structure today. You will type it out so many times over the coming lessons that it will start to feel automatic.
Every statement inside main ends with a semicolon. It is easy to forget at first, so if your code will not run, a missing semicolon is one of the first things worth checking.
Quick check
Q1 What is the special method where every Java program begins running?
Q2 What must the class name match?
Want to save your progress? It's free.
Create a free account