Skip to content

VOL 01 / CH 01 / LESSON 02

1.2 Java Code, Line by Line ​

Prerequisites: You have run Hello World

Estimated time: 20 minutes

Scope: The traditional entry point used in Java 17 projects

You are ready to continue when: You can explain classes, entry methods, output statements, and scope in your own words

java
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

public class HelloWorld ​

This line declares a top-level class.

FragmentCurrent Meaning
classDeclare a class; a class can organize data and methods
HelloWorldClass name, chosen by the programmer, Java is case-sensitive
publicThis top-level class can be accessed by code in other packages

A public top-level class also has a file rule: it must be in a source file with the same name. Therefore, public class HelloWorld should be placed in HelloWorld.java.

This does not mean a source file can only declare one class. A compilation unit can contain multiple top-level types, but at most one public top-level type, and public types must correspond to the file name. Keeping "one class per file" is clearest during the initial stages.

public static void main(String[] args) ​

In the traditional Java 17 style used in this volume, java -cp out HelloWorld will locate this entry method and call it.

FragmentPurposeNext Chapter
publicAllows the launcher to access this methodChapter 7
staticThe method belongs to a class; the HelloWorld object does not need to be created before calling the methodChapter 7
voidThe method does not return a Java value upon normal terminationChapter 5
mainThe name of the entry point as agreed upon by the launcherRemember this for this lecture
String[] argsReceives an array of strings for command-line parametersChapter 6

static is not "a method that is already created when the program starts." A more accurate statement is: it is a class method, which can be called through the class itself, without depending on any instance.

The parameter variable does not have to be named args; the following can also serve as the entry point:

java
public static void main(String[] words) {
    System.out.println(words.length);
}

Array brackets can also be written after the variable name, and String words[] is syntactically valid. However, Java code typically uses String[] words, as the type is easier to read. The variable-length parameter syntax String... words will also compile into an acceptable entry signature. Beginners are advised to uniformly use String[] args.

If you still have the same HelloWorld.java, you can recompile and pass two parameters:

bash
java -cp out HelloWorld north east

The array contains north and east. If you kept the greeting program at the top of this page, it still prints the greeting. If you replaced it with the words.length version above, it prints 2.

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

Looking from left to right:

  1. System is a standard library class in the java.lang package; java.lang is automatically imported by the compiler.
  2. out is the standard output stream exposed by System, with a type of PrintStream.
  3. println(...) calls a method of the output stream, writes the parameters, and ends the current line.
  4. "Hello World!" is a string literal; the double quotes themselves are not part of the output content.
  5. ; ends this method call statement.

Comparing with print:

java
System.out.print("A");
System.out.print("B");
System.out.println("C");

Output is:

text
ABC

println uses the line separator appropriate for the current platform. It is not simply appending the same character on all systems.

Curly braces denote the boundaries of a structure ​

java
public class HelloWorld {                    // Class body begins
    public static void main(String[] args) { // Method body begins
        System.out.println("Hello World!");
    }                                        // Method body ends
}                                            // Class body ends

The outer structure opened first and is closed last:

text
HelloWorld class
└── main method
    └── println call

Compilers primarily rely on tokens and braces to understand structure, and indentation does not affect Java semantics. However, indentation can help identify nesting relationships and catch missing one } earlier. This repository uniformly uses four spaces for indentation.

// is a Single-Line Comment ​

java
// This line is visible to the reader, but the compiler will not treat it as an executable statement
System.out.println("Hello World!"); // Comments can also appear at the end of a line

Comments should explain "why," not just repeat code verbatim. File name hints can be written outside of code blocks to prevent beginners from thinking that comments are a necessary part of the program.

Python vs C++ Comparison ​

Python commonly uses indentation to define code blocks:

python
def main():
    print("Hello World!")

if __name__ == "__main__":
    main()

Java uses curly braces to define structure, while Python incorporates indentation into its syntax. The guard in the Python example is a common convention, not every Python file must have an entry declaration.

C++'s entry point returns int:

cpp
#include <iostream>

int main() {
    std::cout << "Hello World!\n";
}

Exiting normally from main is equivalent to returning 0. Java's traditional main returns void; if you want to report a non-zero exit status to the operating system, you can explicitly call System.exit(code), but this is not required for this lesson.

Professional Quick Reference ​

Need to ConfirmShort Answer
Source filenamePublic top-level class name + .java
Traditional entrypublic static void main(String[] args)
Standard outputSystem.out
Print and end current lineprintln
Class body, method body boundariesPaired curly braces
Command-line argumentsString elements in args

Before Moving On ​

Without looking at the code, try to explain why static makes the entry point object-free, why args is not a keyword, what the difference is between print and println, and why public top-level classes should correspond to file names. If you don't understand a term, go back to the corresponding section. There's no need to memorize the entire entry signature.

Next, we’ll check the syntax rules that commonly cause confusion.

→ Next: Basic Java Syntax Rules

Built with VitePress | Software Systems Atlas