Java Tutorial
Module 1: Getting Started
Write Your First Java Program
Create, compile, and run a simple Java application.
8 minute lessonBeginner to intermediate
Create a file named HelloWorld.java. In Java, the source filename must match the name of a public top-level class.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}
Understand the code#
public class HelloWorlddeclares a class namedHelloWorld.mainis the standard entry point used to start this simple application.System.out.println(...)prints text followed by a new line.- The braces
{}mark the start and end of code blocks. - The semicolon
;ends each statement.
Compile and run it#
Open a terminal in the directory containing the file. Run these commands in order:
javac HelloWorld.java
java HelloWorld
The first command creates HelloWorld.class if compilation succeeds. The second starts the class; do not add .class to the command.
Expected output:
Hello, Java!
Common beginner errors#
- Filename mismatch: save the public class as
HelloWorld.java. - Missing semicolon: Java statements such as the print statement need a semicolon.
- Wrong directory: run the commands in the directory containing the source file, or provide the correct path.
- Using
java HelloWorld.javain a compile-first workflow: for this course, compile withjavacfirst and run the class name withjava.
Practice#
Change the text to your name and compile the program again. Then print two lines using two System.out.println statements.