Skip to content
Study Hall
Lesson 1 of 3Programming Basics
Unit 2 · Lesson 1 of 3

Your First Java Program

Every Java program starts from the same skeleton. Learn what each word in that skeleton does, how to compile and run it, and how to tell the three kinds of error apart.

5 min read11 practice questionsAsk AI about this →

Key things to remember

  1. 1Every Java program lives in a class, and execution starts at public static void main(String[] args).
  2. 2The file name must exactly match the public class name, including capitals: public class Hello goes in Hello.java.
  3. 3Braces { } group statements into blocks; a semicolon ; ends one statement. Braces take no semicolon.
  4. 4javac Hello.java compiles to Hello.class; java Hello runs it — no file extension on the run command.
  5. 5println prints then moves to a new line; print prints and leaves the cursor in place.
  6. 6Three error types: syntax (caught at compile time), runtime (crashes mid-run), logic (runs fine, answer is wrong).

A Java program is a set of written instructions that a machine carries out in order, from top to bottom. Before any of those instructions can run, Java insists that they live inside a class, and that the starting instruction lives inside a method with an exact name. That skeleton looks like a lot of ceremony for a program that only prints one line, but every word of it is doing a job, and once you know what those jobs are the skeleton stops being something you copy and starts being something you read.

public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello, world!");
    }
}
The smallest complete Java program. Saved as Hello.java, it prints one line.
Every Java program lives inside a class, and the work starts in main.public class HelloWorld { public static void main(String[] args) { System.out.print("Hi!"); }}12341class declarationfile: HelloWorld.java2the main methodevery program starts here3one statementa semicolon ends every one4closing bracesevery opening { needs a }The main method signature, part by partpublicany code maycall itstaticno object has toexist firstvoidhands nothingback to the callermain(String[])the exact namethe JVM looks forThe public class name and the file name must match exactly, capital letters included.Class HelloWorld in a file called helloworld.java will not compile.
Fig 1Every part of the Java skeleton and the job it does.
PartWhat it meansWhat happens if you leave it out
publicVisible to code anywhere, including the launcher that starts your programThe launcher cannot see main, so the program refuses to start
class HelloDeclares a class named Hello — the container that holds everythingNothing can be written at all; Java has no code outside a class
staticBelongs to the class itself, so it can run before any object existsJava would need an object to call main on, and there is none yet
voidThis method hands no value back when it finishesThe launcher would not know what to do with a returned value
mainThe exact name the launcher looks for — the starting pointThe program compiles but will not run
String[] argsA list of words typed after the program name on the command lineThe signature no longer matches, so main is not found
{ }Group statements into a block; every brace that opens must closeThe compiler reaches the end of the file still waiting for the close
;Ends one statement, the way a full stop ends a sentenceA syntax error — but note that braces never take a semicolon
The skeleton word by word, plus the two pieces of punctuation that run through all of Java.
The file name must match the public class name
A file holding public class Hello must be saved as Hello.java — same spelling, same capitals, no exceptions. Java stores the compiled result as Hello.class and finds classes by their file name, so a mismatch is a compile error before a single line runs. If you rename the class, rename the file in the same moment.

Printing, compiling and running

System.out is the standard output stream — normally the console window. println prints its argument and then moves the cursor to a new line, while print prints and leaves the cursor exactly where it stopped, so the next thing printed continues on the same line. System.out.println(); with empty brackets prints nothing and then ends the line, which is how you leave a blank line between sections of output.

public class Greeting {
    public static void main(String[] args) {
        System.out.print("Hello");
        System.out.print(" there");
        System.out.println("!");
        System.out.println("Next line");
    }
}
Output: Hello there! on the first line, then Next line on the second.
StepCommandReadsProduces
Compilejavac Hello.javaHello.java (your source)Hello.class (bytecode)
Runjava HelloHello.classOutput on the console
Java is compiled, so running a program takes two separate steps: javac translates your source into bytecode, and java feeds that bytecode to the Java Virtual Machine. You run the class name, with no .java and no .class on the end.

The three kinds of error

The later an error shows itself, the more it costs you.you type itit runsit shipsSYNTAXBefore the program runs at allprint("hi" ← missing bracketPython refuses to startRUNTIMEPart-way through, at the failing linemarks[6] on a 6-item listCrashes with a tracebackLOGICNever — it runs and looks finetotal = total * m, meant +Wrong answer, no warningOnly testing against answers you worked out yourself will find a logic error — the computer will never tell you.
Fig 2Syntax, runtime and logic errors, and the stage at which each one shows up.
Error typeWhen it appearsExampleHow you find it
SyntaxAt compile time — the program never runsMissing ;, unmatched }, System.out.printnThe compiler names the file and line
RuntimeWhile running — the program stops part wayDividing an int by zero, reading past the end of an arrayAn exception message plus a stack trace
LogicNever announced — the program runs perfectlyUsing + where you meant -, averaging by the wrong countOnly by testing with values whose answer you already know
Logic errors are the dangerous ones
A syntax error is loud and immediate, and a runtime error at least tells you where it died. A logic error produces a confident wrong answer with no complaint at all. This is why you test with inputs whose correct output you can work out by hand: a program that prints something is not the same as a program that works.

Comments

public class Payslip {
    public static void main(String[] args) {
        // Single-line comment: everything after // is ignored.
        double rate = 17.20;   // hourly rate in dollars

        /* A block comment can run
           across several lines. */
        double hours = 12.5;
        System.out.println(rate * hours);
    }
}
Two comment styles. The compiler skips both completely.

Comments exist for the human reading the code later, and that human is usually you. A good comment explains why a line is there, not what it plainly does — // convert to cents to avoid rounding drift earns its place, while // add one to i does not. Comments are also a debugging tool: commenting out a suspect block temporarily removes it without deleting it, which lets you test whether it was the cause.

Worked examples

Reveal one step at a time and try to beat it to the next line.

Example 1
A file named Average.java contains public class average { ... } and will not compile. Identify every problem and fix it.
Example 2
Predict the exact console output of this program, line by line.
Example 3
A program that should print the area of a rectangle prints the perimeter instead. Classify the error and describe how you would find it.

Where marks get lost

  • Saving a file under a name that does not match the public class name — Java rejects it before it looks at anything else.
  • Typing java Hello.java instead of java Hello when running, or forgetting to compile first so the .class file is stale or missing.
  • Leaving off a semicolon, or adding one after a closing brace. Statements end in ;; blocks do not.
  • Writing System.out.println with a lowercase s or a misspelled printn — Java is case sensitive and will not guess.
  • Assuming that because a program printed something, it worked. Only a test with a known correct answer tells you that.

Flashcards 10

What is the exact signature Java looks for to start a program?
Why must the file name match the class name?
javac versus java
print versus println
+ 6 more

Practice

1
Which of these is the correct signature for the method where a Java program starts?
2
A file declares public class Calculator. What must the file be named?
3
What appears on screen after System.out.print("Ja"); System.out.print("va"); runs?
4
A student forgets a semicolon at the end of a line. What kind of error is this?
5
A program compiles, runs to the end, and prints an average of 45 when the correct average is 72. This is best classified as:
6
Which command runs a compiled program whose class is named Budget?
7
Put the steps of getting a Java program running into order.
  1. 1Run java ClassName to launch the bytecode
  2. 2A ClassName.class file of bytecode is produced
  3. 3Fix any syntax errors the compiler reports and recompile
  4. 4Write the source code and save it as ClassName.java
  5. 5Run javac ClassName.java to compile it
8
Match each piece of the Java skeleton to its job.
class
static
void
String[] args
9
What file does javac Hello.java produce?
10
Which line is a legal Java comment?
11
Which of these would produce a runtime error rather than a compile error?

Spot a mistake on this page? Let us know