Java tutorialLesson 2 of 18 · tap to see all lessons
Java tutorial · Beginner
Java Program Structure and Syntax: Your First Program Line by Line
Understand every line of a first Java program: classes, main, statements, comments, identifiers, keywords, and the three kinds of errors.
- Qyubie Learn Editorial Team
- Published
- 8 min read
Includes 4 quick checks you can do right here.
Java's first program looks long compared with Python's one-liner, but every word has a job. In this lesson we take it apart line by line. Then we cover the rules every Java file follows: statements, comments, names, keywords, and the kinds of errors you'll meet.
By the end of this lesson you will be able to:
- explain each part of a basic Java program,
- tell the difference between
printandprintln, - write comments and choose valid names, and
- tell a syntax error from a runtime error and a logic error.
Running the examples: Java can't run on this page, so the practice here is predicting output, a skill exams test constantly. To run Java yourself, use the IDE you set up in lesson 1.
The whole program
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}Output:
Hello, world!Line by line
public class Hello {: Java code lives inside classes. This declares a class named Hello. Because it is public, the file must be named Hello.java. The { opens the class body; its matching } is the last line.
public static void main(String[] args) {: the main method, where the program starts. You'll write this line in every program for now. The words mean:
| Word | Meaning (short version) |
|---|---|
public | can be called from outside the class (the JVM needs to call it) |
static | belongs to the class itself, so no object is needed to call it |
void | returns nothing |
main | the special name the JVM looks for to start the program |
String[] args | command-line arguments, as an array of text |
System.out.println("Hello, world!");: prints text and then moves to a new line. Text in double quotes is a String. Every statement ends with a semicolon.
} }: close the method, then the class.
Quick check
print vs println
println prints and then ends the line. print prints and stays on the same line.
System.out.print("A");
System.out.print("B");
System.out.println("C");
System.out.println("D");Output:
ABC
DQuick check
Statements and expressions
A statement is one complete instruction, and it ends with ;. An expression is a piece of code that produces a value, such as 2 + 3, price * 2, or "Hi " + name. Statements are often built from expressions:
int price = 50; // statement: declare and store a value
int total = price * 3 + 10; // the right side is an expression
System.out.println(total); // statement: call a methodOutput:
160A block is a group of statements inside { }. Class bodies, method bodies, and (later) if and loop bodies are all blocks.
Comments
Comments are notes for people. The compiler ignores them.
// A single-line comment: everything after // is ignored.
/* A multi-line comment
can span several lines. */
/**
* A documentation (Javadoc) comment, placed above classes and methods.
* Tools turn these into web-page documentation.
*/
public class Notes {
public static void main(String[] args) {
System.out.println("Comments don't print"); // they can follow code too
}
}Output:
Comments don't printGood comments explain why, not what. // add 1 to count above count++; adds nothing, but // skip the header row helps.
Identifiers and naming rules
An identifier is a name you choose for a class, method, or variable. The rules:
- Use letters, digits,
_, and$. - Don't start with a digit:
2ndPlaceis invalid,place2is fine. - Don't use spaces or symbols like
-or#. - Don't use a keyword (see below).
- Names are case-sensitive:
score,Score, andSCOREare three different names.
The conventions every Java programmer follows (not enforced, but expected):
| Kind | Style | Example |
|---|---|---|
| Class | PascalCase | StudentRecord |
| Variable, method | camelCase | finalGrade, computeAverage() |
| Constant | UPPER_SNAKE_CASE | MAX_STUDENTS |
Quick check
Keywords
Keywords are words with a fixed meaning in Java, so you can't use them as names. You've already seen several: public, class, static, void, int. Others you'll meet in this course include:
if else switch case for while do break continue return new this final private protected extends implements interface abstract try catch finally throw throws import package
true, false, and null aren't technically keywords, but they're reserved values, so you can't use them as names either.
Three kinds of errors
1. Syntax (compile-time) errors. The code breaks Java's grammar, so javac refuses to compile it and nothing runs. Examples: a missing ;, unmatched braces, or a misspelled keyword.
System.out.println("Hello")error: ';' expected2. Runtime errors. The code compiles, but something goes wrong while it runs, and Java stops with an exception. For example, dividing an integer by zero:
int students = 0;
int perGroup = 30 / students;Exception in thread "main" java.lang.ArithmeticException: / by zero3. Logic errors. The program compiles and runs without crashing but gives the wrong answer. These are the hardest to find, because Java doesn't complain:
int quiz1 = 80;
int quiz2 = 90;
double average = quiz1 + quiz2 / 2; // meant (quiz1 + quiz2) / 2
System.out.println(average);Output:
125.0Division happens before addition, so this computes 80 + 45. Parentheses fix it: (quiz1 + quiz2) / 2.
Quick check
Common mistakes
- Missing semicolon at the end of a statement: the compiler reports
';' expected. - Wrong capitalization.
system.out.printlnandstringwon't compile. It'sSystemandString. - File name ≠ public class name.
- Unmatched braces. Every
{needs a}. Indenting consistently makes this easy to see. - Smart quotes from a word processor (
“Hello”): Java needs plain"quotes.
Summary
- A Java program is a class with a
mainmethod, and execution starts inmain. printlnends the line;printdoesn't.- Statements end with
;, and blocks are wrapped in{ }. - Comments:
//,/* */, and/** */for documentation. - Identifiers can't start with a digit or be keywords, and they're case-sensitive.
- Syntax errors stop compiling, runtime errors crash a running program, and logic errors give wrong answers.
Next lesson: variables, constants, and data types.