Courseiva
1Z0-811Chapter 3 of 16Objective 1.3

Writing and Running Your First Java Program

The 1Z0-811 exam objective "Write, compile, and run a simple Java program that prints output to the console" is the first real hurdle you face. Without mastering this flow, you cannot test any other Java concept because you will never see if your code actually works. This chapter gives you the exact steps to go from an empty screen to a working program that says "Hello, World!"—the same foundation every professional Java developer uses daily.

12 min read
Beginner
Updated Jul 23, 2026
Reviewed by Johnson Ajibi· Senior Network & Security Engineer · MSc IT Security

A simple way to picture Writing and Running Your First Java Program

The First-Time Chef Analogy

A head chef in a busy restaurant kitchen decides to teach a new line cook how to serve a dish to a customer. The chef does not just let the cook shout across the room. Instead, the chef writes the recipe on a slip of paper, hands it to the cook, and says, "Follow this exactly." The cook reads the recipe, which tells them to chop vegetables, heat the pan, and plate the food. Once the cook has done all that, the chef inspects the finished plate, makes sure there are no mistakes, and only then hands the plate to the waiter to take to the customer.

Now map that to Java. The chef is you, the programmer. The recipe slip is the source code you write in a text file. The cook reading and following the recipe is the compiler, which translates your human-readable Java instructions into bytecode. The chef inspecting the plate is the Java Virtual Machine (JVM) checking that the bytecode is safe and ready to run. The waiter delivering the plate to the customer is the JVM executing the program so the output appears on your screen. Every step—writing the recipe, checking it, delivering it—happens before the diner ever tastes the food. In Java, you write the code, compile it into bytecode, and finally run it to see output.

How It Actually Works

When you start learning Java, the biggest mystery is how your typing turns into something a computer understands. Let us break that down layer by layer.

First, you need a text editor. This is any program that lets you type and save plain text—Notepad on Windows, TextEdit on Mac, or a code editor like VS Code. You will write your Java instructions in a file and save it with a name ending in ".java". For example, you might create a file called "HelloWorld.java".

Inside that file, you write what is called "source code". Source code is the set of instructions you want the computer to carry out, written in the Java programming language. The Java language uses specific words and punctuation that the computer expects to see. The most important structure is a "class". In Java, everything lives inside a class. Think of a class as a container that holds your code. The class name must match the file name exactly. If your file is "HelloWorld.java", your class must be called "HelloWorld" with the same capitalisation.

Every Java program needs an entry point—a special method called "main". A method is a block of code that performs a specific task. The main method is where the Java Virtual Machine starts executing your program. It always looks like this:

public static void main(String[] args)

Do not worry about memorising the meaning of each word just yet. For now, treat it as the magic phrase that says "start here". Inside the main method, you put the instructions you want the computer to perform.

The most basic instruction is to print something to the console. The console is a text-based window where your program can display messages. In Java, you print to the console using the instruction:

System.out.println("Hello, World!");

This single line tells the computer to output the text "Hello, World!" followed by a new line. The semicolon at the end is like a full stop—it marks the end of that instruction.

Once you have written your source code and saved it, you cannot run it immediately. You have to "compile" it first. Compilation is the process of converting your human-readable Java source code into "bytecode", which is a lower-level set of instructions that the Java Virtual Machine can understand. The compiler is a program called "javac" (short for Java compiler). You run it from a terminal or command prompt by typing:

javac HelloWorld.java

If there are no errors, the compiler produces a new file called "HelloWorld.class". This .class file contains the bytecode. You cannot read it easily with a text editor, but the JVM can.

Now you are ready to run the program. You use the "java" command followed by the class name (without the .class extension):

java HelloWorld

This launches the Java Virtual Machine, which loads your bytecode and executes the instructions. If everything is correct, you will see "Hello, World!" printed in the terminal window.

The entire flow—write code, compile to bytecode, run with JVM—is why Java is called a "compiled and interpreted" language. The compilation step checks for many errors before the program ever runs, which catches mistakes early. The JVM then interprets the bytecode, which makes Java programs portable across different operating systems. A single .class file can run on Windows, Mac, Linux, or any system that has a JVM installed.

Errors can happen at any stage. A "compile-time error" is a mistake in your source code that the compiler catches, such as a missing semicolon or a misspelled word. The compiler will tell you the line number and a description of the problem. A "runtime error" happens while the program is running, like trying to divide a number by zero. The program will crash and display an error message called a "stack trace".

To print output, you have two common variations of the print command:

System.out.println() prints the text and then moves the cursor to a new line.

System.out.print() prints the text but stays on the same line, so the next output appears right after.

You can also print numbers and the results of calculations. For example:

System.out.println(5 + 3); prints "8".

Every Java program you write will follow this same pattern: write source code inside a class with a main method, compile with javac, and run with java. Once you memorise this pattern, you can move on to experimenting with more complex instructions.

The three-stage process of writing, compiling, and running a Java program: source code, compilation to bytecode, and execution by the JVM to produce console output.

Walk-Through

1

Create the source file

Open a plain text editor and create a new file. Type the class declaration and main method exactly as shown. Save the file with a .java extension, using the same name as the class. For example, save as 'HelloWorld.java'.

2

Write the print statement

Inside the main method, add the line 'System.out.println("Hello, World!");'. This instruction tells the computer to output the message to the console. The semicolon at the end is crucial—it marks the end of the statement.

3

Open the terminal or command prompt

On Windows, open Command Prompt or PowerShell. On Mac or Linux, open Terminal. Navigate to the folder where you saved the .java file using the 'cd' command. For example, 'cd Desktop' if the file is on the desktop.

4

Compile the source file

Type 'javac HelloWorld.java' and press Enter. The Java compiler (javac) reads your source code and checks for errors. If there are no errors, it produces a file called 'HelloWorld.class' in the same folder. If there are errors, the terminal will show a message indicating the problem and line number.

5

Run the compiled program

Type 'java HelloWorld' (without the .class extension) and press Enter. The Java Virtual Machine loads the bytecode from HelloWorld.class and executes the main method. You will see the output 'Hello, World!' printed on the next line in the terminal.

6

Verify and debug if needed

If you see an error message, read it carefully. Common errors include misspelling the class name, forgetting a semicolon, or typing the wrong command. Correct the mistake in the .java file, save it, and repeat the compile and run steps until the program works.

What This Looks Like on the Job

Imagine you join a small software company as a junior developer. Your first task is to fix a bug in a program that calculates customer discounts. The program prints the wrong discount amount to a log file. Your boss hands you a folder containing the Java source files.

Your first step is to open the relevant file—let us call it "DiscountCalculator.java"—in your code editor. You read the code and spot a mistake: the discount percentage is stored as an integer instead of a decimal, so any discount less than 1% is lost. You change the data type from "int" to "double", which allows decimal values. Then you add a System.out.println() statement to print the calculated discount to the console so you can verify the result. You write:

System.out.println("Calculated discount: " + discountAmount);

Next, you need to compile the changed file. You open the terminal, navigate to the folder containing DiscountCalculator.java, and type:

javac DiscountCalculator.java

The compiler runs. You see no error messages, so a new DiscountCalculator.class file appears.

Now you want to test your fix. You run the program with:

java DiscountCalculator

The program executes, and you see your print statement output "Calculated discount: 0.15" in the terminal. That looks correct. But you are not done yet. You need to ensure the whole program works end-to-end. The program also reads customer data from a file and writes the final invoice to a report. You run it with sample data and check that the printed output matches the expected values.

Your company uses a build tool called Maven to automate compilation and running tests. You learn to run "mvn compile" instead of typing javac manually. But the underlying principle is identical: the tool calls javac for you. When you commit your changes to the team's code repository, the build server automatically compiles the entire project. If there is a compile error, the build fails and the team gets an email.

In a real job, you rarely write a program from scratch. You spend most of your time reading existing code, adding print statements to understand what the program is doing (a technique called "debugging with print statements"), and then running the program to test your changes. The write-compile-run loop is the heartbeat of your daily work. Every professional Java developer has this loop muscle-memorised.

When you need to print output for debugging, you might use System.out.println() hundreds of times in a single day. Later, you will learn about logging frameworks that replace print statements, but the fundamental concept of sending text to an output stream remains the same. The exam only expects you to know the basic print commands and the compile-run sequence.

How 1Z0-811 Actually Tests This

The 1Z0-811 exam tests objective 1.3 with specific question patterns. You will not be asked to memorise every word of the main method signature, but you will be expected to recognise it and know what it means. The exam asks questions in these categories:

Identifying the correct structure of a Java class. They will show you a code snippet missing the class declaration or the main method, and ask which line is missing or which part is incorrect.

Choosing the correct command to compile a Java file. They will give you a file name like "MyProgram.java" and ask which command produces the .class file. The answer is always "javac MyProgram.java".

Choosing the correct command to run a Java program after compilation. The answer is always "java MyProgram" (without the .class extension).

Determining what a simple program prints to the console. They will give you a short code snippet with System.out.println() and ask what the output is.

Recognising the difference between compile-time errors and runtime errors. They might show a missing semicolon and ask whether it causes a compile-time or runtime error.

Identifying the components of the main method signature. They may ask which of these is the correct declaration: "public static void main(String[] args)" or a slight variation. The correct answer must have all four keywords in order: public, static, void, main, and the parameter "String[] args".

Traps the exam loves to set include:

Using the wrong case for the class name when running the program. The exam might say you saved "HelloWorld.java" but run "java helloworld". That fails because Java is case-sensitive.

Forgetting that System.out.println() moves to a new line after printing, while System.out.print() does not. They will ask what the output is from a snippet that mixes both.

Showing a program where the class name and file name do not match, and asking if it compiles. It does not.

Including extra characters like a missing semicolon, wrong brackets, or an extra closing brace.

Asking what happens if you run "java MyProgram.class" instead of "java MyProgram". The answer is an error.

Key definitions to memorise:

Source code: The human-readable Java instructions in a .java file.

Bytecode: The compiled instructions in a .class file, understood by the JVM.

Compiler (javac): The tool that translates source code into bytecode.

JVM: The Java Virtual Machine that runs the bytecode.

Command line: The text-based interface where you type javac and java commands.

System.out.println(): A statement that prints a line of text to the console.

To prepare, practise writing a tiny program from memory at least ten times: create a file, write the class, write the main method, write a print statement, compile, and run. Time yourself. In the exam, you will not actually compile or run anything, but you will need to read code and predict the outcome without the computer's help. That skill comes from doing it in real life.

Key Takeaways

A Java source file must have the same name as the public class inside it, including matching capitalisation.

The main method signature 'public static void main(String[] args)' is the required entry point for every standalone Java program.

The command 'javac YourFile.java' compiles the source file into a .class file containing bytecode.

The command 'java YourFile' runs the compiled bytecode using the Java Virtual Machine without the .class extension.

System.out.println() prints its argument and moves the cursor to a new line, while System.out.print() stays on the same line.

A missing semicolon at the end of a statement causes a compile-time error, which prevents the .class file from being created.

The JVM is platform-independent, meaning a .class file compiled on Windows can run on a Mac if a JVM is installed.

Every Java instruction inside a method must end with a semicolon, acting like a full stop in English.

Comments in Java, preceded by // for a single line or /* */ for multiple lines, are ignored by the compiler and do not affect execution.

The first program most developers write is a 'Hello, World!' program because it confirms the entire toolchain works correctly.

Easy to Mix Up

These come up on the exam all the time. Here's how to tell them apart.

javac command

Compiles .java files into .class bytecode files

Requires the .java extension in the command argument

Produces a new file on disk if successful

java command

Runs the bytecode in the .class file using the JVM

Requires the class name without any file extension

Does not create any new files; only executes code

Compile-time error

Detected by the compiler during the javac step

Prevents the .class file from being created

Examples: missing semicolon, misspelled keyword

Runtime error

Occurs while the program is running after compilation

The .class file exists but the program crashes during execution

Examples: dividing by zero, trying to access an invalid array index

System.out.println()

Prints the argument and then moves to the next line

Automatically appends a newline character

Commonly used for separate output messages on distinct lines

System.out.print()

Prints the argument without moving to the next line

Does not append a newline character

Useful for building a line of output piece by piece

Source code (.java file)

Human-readable text written by the programmer

Requires the javac tool to be converted

Platform-independent in terms of writing, but tied to the Java language

Bytecode (.class file)

Machine-readable instructions for the JVM

Produced by the compiler from source code

Platform-independent; can run on any system with a JVM

Watch Out for These

Mistake

You must write 'System.out.println' exactly as it appears, including capital letters, but you can add extra spaces anywhere.

Correct

Java is space-insensitive between tokens, but the keyword 'println' must have exactly that lowercase spelling. 'Println' or 'PrintLine' will not compile.

Beginners often think capitalisation is optional in programming because they have seen inconsistent naming in everyday writing.

Mistake

The file name and class name must be the same, but capitalisation does not matter.

Correct

Both the spelling and the capitalisation must match exactly. If the class is 'MyClass', the file must be 'MyClass.java' with the same M, C, and other letters.

On Windows, the file system is case-insensitive, so beginners mistakenly think Java behaves the same way. It does not.

Mistake

After typing 'javac HelloWorld.java', you run the program by typing 'HelloWorld' with no command.

Correct

You must use the 'java' command first: 'java HelloWorld'. Just typing the name alone does nothing in the terminal.

The natural instinct is to think the .class file is an executable you can double-click or type directly, but Java requires the JVM to launch it.

Mistake

The main method can be written anywhere inside the class, like at the bottom or in the middle.

Correct

The JVM will find the main method regardless of where it appears inside the class, but it must be declared exactly as 'public static void main(String[] args)' for the JVM to recognise it as the entry point.

Some languages require a specific placement (like Python's 'if __name__ == "__main__":' at the bottom), so beginners assume Java is similar.

Mistake

You can write multiple classes in a single .java file, and as long as one of them has a main method, the program will run.

Correct

You can have only one public class per file, and that class name must match the file name. Additional non-public classes are allowed, but they cannot have the same name as the file. The main method must be inside the public class that matches the filename.

Beginners see examples online with multiple classes in one file and assume it is always allowed, not realising the restrictions on public classes.

Mistake

System.out.println() only works with text inside double quotes. You cannot print numbers or variables.

Correct

System.out.println() can print any data type—numbers, boolean values, or variables—by passing them directly as arguments. For example, System.out.println(42) prints 42.

If the only example a beginner has seen is System.out.println("Hello"), they mistakenly think the parentheses only accept quoted text.

Do You Actually Know This?

Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.

Frequently Asked Questions

What is the difference between System.out.println and System.out.print?

System.out.println prints the text and then moves the cursor to a new line, so the next output starts on a fresh line. System.out.print prints the text and leaves the cursor on the same line, so the next output continues immediately after.

Why do I get an error when I try to run 'java HelloWorld.class'?

The 'java' command expects the class name, not the file name. You should type 'java HelloWorld' without the .class extension. Adding .class makes the JVM look for a class called 'HelloWorld.class', which does not exist.

Do I have to compile my Java file every time I change it?

Yes. Every time you modify the .java source file, you must run 'javac' again to produce an updated .class file. Running 'java' without recompiling will execute the old bytecode, so your changes will not appear.

What does 'public static void main(String[] args)' mean in plain English?

It tells the JVM that this method is the program's starting point. 'public' means it can be accessed from outside the class. 'static' means it belongs to the class itself, not to any individual object. 'void' means it does not return a value. 'String[] args' allows the program to accept command-line arguments.

Can I name my Java file something different from the class name?

No. If the class is declared as 'public class MyProgram', the file must be called 'MyProgram.java'. If the names do not match, the compiler will produce an error. Non-public classes can have different file names, but the public class must match.

Why does my terminal say 'javac is not recognized' when I type javac?

This means the Java Development Kit (JDK) is either not installed or not added to your system's PATH variable. Install the JDK from Oracle's website, and during installation, ensure you select the option to add Java to your PATH. Then restart your terminal.

What is the point of the 'String[] args' part if I do not use it?

Even if you do not use command-line arguments, the main method signature must include it because the JVM expects that exact signature. It is part of the language specification. If you omit it, the JVM will not recognise your method as the entry point and will report an error.

Terms Worth Knowing

Keep going

You've finished Writing and Running Your First Java Program. Continue through the 1Z0-811 study guide to build a complete picture of the exam.

Done with this chapter?