Java · Beginner
Java Syntax and Your First Program
In short: A Java program is a class that contains a public static void main(String[] args) method; the Java Virtual Machine starts there and runs its statements from top to bottom. The source lives in Main.java, javac compiles it to bytecode and java runs it.
Anatomy of a Java program
Java does not let you write a bare statement and run it. Every piece of code lives inside a class, and a program starts at one specific method: public static void main(String[] args). When you type java Main, the Java Virtual Machine (JVM) loads the class named Main, looks for that exact method and calls it. If the method is missing or its signature differs, the program does not start.
Each word in that line has a job. public makes the method reachable from outside the class, which the JVM needs. static means the method belongs to the class itself, so the JVM can call it without first creating an object. void says it returns nothing. String[] args receives any command-line arguments as an array of strings; you may ignore it, but it has to be there.
Inside the method the code is a sequence of statements. A statement is one instruction, such as declaring a variable, assigning a value or calling a method, and it ends with a semicolon. Curly braces group statements into a block: the class body, the method body, and later the bodies of if statements and loops. The compiler ignores indentation and line breaks, so a statement may span several lines and two statements may share one; semicolons and braces are what it reads. Consistent indentation is for the humans reading the code.
Java is case-sensitive. System, String and Main start with a capital letter; main, println and int do not. Changing the case produces a different name, and usually one that does not exist.
Printing goes through System.out.println, which writes its argument followed by a line break, and System.out.print, which writes without the break. Reading input is not built into the language; the Scanner class from the java.util package does it, which is why programs that read input begin with an import line.
Running a program takes two steps. javac Main.java compiles the source into Main.class, a file of bytecode. java Main starts the JVM, which executes that bytecode. A compile error, such as a missing semicolon, stops the first step and names the line; only code that compiles ever runs. Since Java 11 the single command java Main.java compiles and runs a one-file program in one go, which is convenient while learning.
Syntax
import java.util.Scanner; // only needed when the program reads input
public class Main { // one public class per file, named like the file
public static void main(String[] args) { // execution starts here
statement; // every statement ends with a semicolon
statement;
}
}The file must be called Main.java because the public class is called Main. // text is a comment to the end of the line and /* text */ can span lines; the compiler ignores both.
The smallest useful program
Two statements inside main, each printing one line.
public class Main {
public static void main(String[] args) {
System.out.println("Corner Bakery opens at 7:00");
System.out.println("Today's special: rye loaf");
}
}Output
Corner Bakery opens at 7:00 Today's special: rye loaf
The class wraps everything and main is where the JVM begins. Each println call is one statement, ends with a semicolon, and prints its text followed by a line break, so two calls give two lines. The apostrophe in Today's needs no special treatment inside double quotes; only a double quote itself would have to be escaped as \".
Reading input and printing a result
The program reads a customer name and a number of loaves. It is run with the input lines Priya and 3.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name = in.nextLine();
int loaves = in.nextInt();
System.out.println("Order for " + name);
System.out.println("Loaves: " + loaves);
System.out.print("Thank you");
System.out.println("!");
}
}Input given to the program: Priya ↵ 3
Output
Order for Priya Loaves: 3 Thank you!
The import line makes the Scanner class available, and new Scanner(System.in) wraps standard input. nextLine() reads a whole line as text; nextInt() reads the next whole number and converts it to an int. The + joins text and a number into one string for printing. print leaves the cursor on the same line, which is why "Thank you" and "!" end up together.
Comments, statements and layout
The same shape with comments, an arithmetic statement, and one statement spread over three lines.
public class Main {
// The program starts in main.
public static void main(String[] args) {
int shelves = 4; /* every statement ends with a semicolon */
int perShelf = 12;
int capacity = shelves * perShelf;
System.out.println("Shelf capacity: " + capacity);
System.out.println(
"Two lines of source,"
+ " one statement"
);
}
}Output
Shelf capacity: 48 Two lines of source, one statement
Comments disappear at compile time. int shelves = 4; declares a variable and gives it a value in a single statement. The last println is one statement because it ends at the one semicolon; the line breaks inside the parentheses mean nothing to the compiler. The + at the start of the continuation line joins the two pieces of text.
Common mistakes
Naming the file differently from the public class
Why it goes wrong: A public class must live in a file with the same name.
public class Mainsaved as Program.java fails withclass Main is public, should be declared in a file named Main.java.Fix: Keep the file name and the public class name identical, including capitalisation: Main.java for class Main.
Leaving out a semicolon or a closing brace
Why it goes wrong: The compiler reports
';' expectedorreached end of file while parsing. It often points at the line after the real mistake, because that is where it first noticed something was wrong.Fix: Look at the line before the one reported. An editor that highlights matching braces catches the missing brace before you compile.
Java · fixint total = 3; // semicolon closes the statement System.out.println(total);Getting the capitalisation wrong
Why it goes wrong:
system.out.println("hi");fails withpackage system does not exist, because Java looks for a package called system instead of the class System.stringandScannerspelledscannerfail the same way.Fix: Match the exact spelling:
System,String,Scannerwith a capital;main,println,intwithout.Declaring main with a different signature
Why it goes wrong:
public void main(String[] args)withoutstaticcompiles, but running it printsMain method is not static in class Mainand stops. Leaving outString[] argsgivesMain method not found in class Main.Fix: Type the signature exactly:
public static void main(String[] args). Only the parameter name may change.Java · fixpublic static void main(String[] args) { // ... }
Where you use this
Every command-line tool, batch job and coding-test submission has this shape: main reads its input, does the work and prints the result. A script that totals a file of sales figures, a converter that reads lines of one format and writes another, and the exercises on this site, which feed test input through standard input and compare what you print, all start from the same skeleton. Once you can write it without thinking, your attention is free for the logic.
A common variant reads every line until the input ends, using hasNextLine() to check whether another line exists. In larger programs main stays short: it reads its arguments, creates a few objects and hands the work to them, which is where the classes and objects lesson picks up.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
String line = in.nextLine();
System.out.println("got: " + line);
}
}
}Key points
- All code lives in a class; execution starts at
public static void main(String[] args). - A statement ends with a semicolon; braces group statements into blocks.
- Java is case-sensitive:
Systemandsystemare different names. printlnprints and ends the line;printprints without a line break.- Reading input needs
import java.util.Scanner;andnew Scanner(System.in). javac Main.javacompiles,java Mainruns; code that does not compile never runs.- Comments (
//and/* */) are for readers and are dropped by the compiler.
Try it yourself
The program prints a fixed greeting. Change it so it reads one line of input, the visitor's name, and prints Welcome, followed by that name. Remember the import.
public class Main {
public static void main(String[] args) {
System.out.println("Welcome");
}
}
MartaWelcome, Martaimport java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name = in.nextLine();
System.out.println("Welcome, " + name);
}
}
Practise this
Exercises for this lesson are in the Java practice set.
Related lessons
- Variables and Data Types in JavaJava's primitive types and String, declaring and initialising variables, var, casting and integer overflow: why the type you pick decides what a value can hold.9 min
- Operators in JavaJava's arithmetic, comparison, logical and assignment operators: integer division, remainder, short-circuit evaluation and precedence, with runnable examples.9 min
- Methods in JavaHow to define and call Java methods: parameters and arguments, return types and void, overloading, variable scope, and why arguments are passed by value.9 min
Frequently asked questions
Why is the main method static in Java?
The JVM calls main before any object exists. A static method belongs to the class rather than to an instance, so it can be called without constructing anything; an instance method would force the JVM to guess how to build a Main object first. Java 21 offers instance main methods only as a preview feature that must be enabled with a compiler flag, so standard programs use the static form.
Do I have to compile Java before running it?
Yes. javac Main.java produces Main.class, and java Main runs it. Since Java 11 the command java Main.java compiles a single source file in memory and runs it in one step, which is handy for small programs; build tools still use the two-step form for projects with many files.
How this page was checked. Every program on it was run with OpenJDK 21 at build time by the publishing checks, and the output shown is what it printed. Running Java inside the browser is not available yet, so the Run button is absent rather than pretending; copy the code and run it with OpenJDK 21 locally.