Java Basics and Your First Program

Every Java program begins the same way, and the distance between an empty file and a running process is shorter than it first appears: one file, one class, one method that the virtual machine knows how to find. What makes Java worth learning carefully at this stage is not the syntax itself but what happens between the text you type and the output you see. By the end of this chapter you will have written and run several programs, and you will be able to explain every step of the pipeline: how the compiler produces bytecode, how the class path decides which classes are visible, what a package declaration changes about the file layout, and what each word of the main method signature is doing.

1. The shape of a Java program

A Java source file holds one top-level class, and the file name has to match the name of the public class it contains. The convention is that the file is named after the class, with a .java extension.

public class Greeting {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}

Read from the inside out. Greeting is a class, which is the unit of packaging in Java. Inside it is a method, which is a named block of code. System.out.println is a call to a method on the standard library that writes a line of text to standard output. The class, the method, the statement, and the value are the four parts that appear in every Java program you will ever write.

Java is statically typed: every variable has a declared type, and every expression has a type that the compiler can check. It is also compiled: nothing runs until a compiler has translated the source into bytecode that the virtual machine can verify. That verification step is why Java errors are usually found before the program starts rather than in the middle of it.

2. Compiling and running

Two commands cover the whole loop.

javac Greeting.java
java Greeting

The first command compiles Greeting.java and writes a Greeting.class file next to it. The second starts a virtual machine, loads that class file, finds the main method inside it, and begins executing from the first statement of that method.

The output is:

Hello, Java!

Here is what the two commands actually did.

  1. The compiler parsed the source. It checked syntax, resolved names, and applied the type rules. Every problem it found was reported before a single instruction ran.
  2. The compiler produced bytecode. The result is not machine code for your processor. It is a .class file containing instructions for the Java platform, a constant pool, and metadata describing the class: its fields, its methods, and their signatures.
  3. The virtual machine loaded the class. On startup, the java launcher locates the class, reads its metadata, and links it.
  4. The launcher found the entry point. It looks for a method with the exact signature public static void main(String[] args). If no such method exists, or if its signature does not match exactly, the run fails with Could not find or load main class or with a main method error, and no program output appears at all.
  5. The method executed. Each statement produced a value, println formatted it, and the output went to standard output.

Because the class file is platform independent, you can copy Greeting.class to a machine with a different processor and run it there, provided that machine has a compatible virtual machine. This is the whole point of the “compile once, run anywhere” model, and it is why the compiler and the runtime versions have to agree.

3. Running a single file without a build step

Since Java 11, the launcher can compile and run a single source file in one command, which is convenient for experiments:

java Greeting.java

The launcher compiles the file in memory and runs the result, without leaving a .class file behind. It only handles one file, and that file cannot depend on other classes outside the standard library, so it is a learning and scripting convenience rather than a way to run an application.

4. Where the class files go

By default javac writes the .class files into the same directory as the source. That gets messy quickly, so the -d flag sets the output directory, and it also sets the package root of the compiled tree.

javac -d out src/com/example/Greeting.java
java -cp out Greeting

The resulting tree mirrors the package structure:

out/
└── Greeting.class

When the class belongs to a package, the output directory contains the package directories, and the class path entry has to be the directory above the package root, not the package directory itself.

javac -d out src/com/example/Greeting.java
java -cp out com.example.Greeting

Getting this wrong is the single most common cause of ClassNotFoundException, and the rule to remember is short: the class path entry is the root of the compiled tree, and the class name you pass to java includes the package.

Other javac flags worth knowing on day one:

FlagEffect
-d dirWrite class files into dir, mirroring the package structure
--release 21Compile for a language and API level, and reject newer APIs
-encoding UTF-8Read the source with a specific character encoding
-Xlint:allTurn on every compiler warning
-parametersKeep parameter names in the class file, which reflection needs

5. The class path

The class path is the list of locations the virtual machine searches for a class it has not loaded yet. It can contain directories of loose class files and JAR archives.

The CLASSPATH environment variable sets the default, and the -cp (or -classpath) flag on the java command overrides it for that run.

export CLASSPATH=out:libs/commons-text-1.12.jar
java com.example.Greeting

The separator is the path separator of the platform: a colon on macOS and Linux, and a semicolon on Windows.

java -cp "out;libs/commons-text-1.12.jar" com.example.Greeting

The current directory is not on the class path by default, which surprises almost everyone the first time. If a program fails with ClassNotFoundException while the class file is sitting right there in the directory you are standing in, the fix is to name the directory explicitly with -cp ..

Java 9 added the module system, which introduced a second, separate path: --module-path for modules, with --add-modules to say which ones the application can read. Most projects still use the class path, and the two can be mixed in a single command, but a modular project should use the module path.

6. Packages and imports

A package is a namespace. It organizes classes, prevents name collisions between libraries, and it maps onto the directory layout on disk.

package com.example.greeting;

public class Greeting {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}

Three rules follow from the declaration.

  • The file must live in a directory that matches the package: src/com/example/greeting/Greeting.java for the package com.example.greeting.
  • The package name must match the directory structure exactly, including case, because the file system and the package name are matched literally.
  • A file can only contain one package declaration, and it must come before any import.

The import statement makes a class from another package visible by its simple name.

package com.example.greeting;

import java.util.List;
import java.util.ArrayList;

public class Greeting {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Java");
        System.out.println(names);
    }
}

There is no need to import java.lang.*: classes in that package, such as String, System and Object, are visible everywhere automatically.

An import can also name a class in the default package, which is the package used when no package declaration is present. Importing everything with a wildcard is legal, but it hides which classes a file actually depends on, so a wildcard is worth using only in a file that genuinely works with a whole package.

import java.util.*;          // legal, but discouraged in application code
import static java.lang.Math.max;   // import one static member

An import is not a compile-time copy of anything. It is a shortcut for the compiler and the reader. At runtime the class is still located on the class path, and a fully qualified name always works even without the import.

java.util.List<String> names = new java.util.ArrayList<>();

7. The main method, word by word

public static void main(String[] args) {
}
PartWhat it meansWhat breaks without it
publicThe method is visible from anywhere, including the launcherThe launcher cannot call it and reports that the main method is not found
staticThe method belongs to the class, not to an instance of itThe launcher would have to construct an object before it could start, which it will not do
voidThe method returns no valueThe launcher ignores the return value, so this is a convention rather than a requirement
mainThe name the launcher looks forNothing happens at all, because no entry point is found
String[] argsThe command line arguments, as an array of stringsThe launcher cannot pass arguments, and the signature no longer matches
argsThe name of that array, chosen by the authorNothing, this is a local name

The array of arguments is how a program receives input from outside itself.

java com.example.Greeting Ada 42

Inside main, args[0] is Ada and args[1] is 42. Because the launcher hands over strings, every argument is parsed as text, and converting a number is your job:

int count = Integer.parseInt(args[1]);

The signature may also be written with the varargs form, String... args, which is the same type as String[] and accepts the same arguments. The launcher recognises both.

8. Comments

Java has three comment forms.

// A single-line comment, ended by the end of the line.

/*
   A block comment, which can span several lines.
   It cannot be nested inside another block comment.
*/

/**
   A documentation comment. The Javadoc tool turns these into API documentation,
   and it understands the @param, @return and @throws tags.
   */
public int add(int left, int right) {
    return left + right;
}

Comments should explain why something is done, not restate what the code does. A comment that says increment the counter above counter++ is noise; a comment that says the service retries at most three times, so this is the last attempt carries information the code does not have.

9. Reading input with Scanner

Scanner reads from any source, including standard input.

import java.util.Scanner;

public class ReadInput {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Name: ");
        String name = scanner.nextLine();

        System.out.print("Age: ");
        int age = scanner.nextInt();

        System.out.printf("%s is %d years old.%n", name, age);
    }
}

The methods come in two families. nextInt, nextLong, nextDouble and nextBoolean read a single token and convert it, and they throw InputMismatchException when the token is not the expected type. nextLine reads the rest of the line as text, and next reads a single whitespace-delimited token as text.

The mixing of the two families is the classic trap. nextInt consumes the number but leaves the newline in the buffer, so a following nextLine returns an empty string. There are two clean fixes: read everything as lines and convert explicitly, or consume the leftover newline.

scanner.nextInt();
scanner.nextLine();     // consume the rest of the line
String rest = scanner.nextLine();

or, more simply, read lines and parse them:

String line = scanner.nextLine();
int age = Integer.parseInt(line.trim());

Also note that Scanner on standard input should not be closed explicitly. Closing it closes System.in for the whole process, and any later read fails.

10. Formatted output

System.out is a PrintStream, and it offers three ways to write.

System.out.print("no newline");
System.out.println("one line");
System.out.printf("%s scored %d points%n", "Ada", 42);

printf uses format specifiers, and the same syntax is available through String.format when you want a string rather than output.

SpecifierMeaningExample
%sAny object, converted with toStringAda
%dInteger in base ten42
%,dInteger with thousands separators1,234,567
%.2fFloating point with two decimal places3.14
%bBooleantrue
%cCharacterA
%xInteger in hexadecimalff
%%A literal percent sign%
%nThe line separator of the platforma newline

The specifiers are matched positionally against the arguments, and the index form changes the order when you need it: %2$s is the second argument and %1$s is the first.

System.out.printf("%2$s scored %1$d points%n", 42, "Ada");

Width and alignment are controlled by flags: %-10s left aligns in a field of ten characters, %10s right aligns, and %08.3f pads a number with leading zeroes to eight characters in total.

11. A slightly larger program

The following program puts the pieces together: it reads a name and three scores, computes an average, and prints a formatted summary.

import java.util.Scanner;

public class GradeReport {

    private static double average(double... scores) {
        if (scores.length == 0) {
            return 0;
        }
        double total = 0;
        for (double score : scores) {
            total += score;
        }
        return total / scores.length;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Student name: ");
        String name = scanner.nextLine();

        System.out.print("Score 1: ");
        double first = scanner.nextDouble();
        System.out.print("Score 2: ");
        double second = scanner.nextDouble();
        System.out.print("Score 3: ");
        double third = scanner.nextDouble();

        double result = average(first, second, third);

        System.out.printf("%n%s%n", name);
        System.out.printf("Average: %.2f%n", result);
        System.out.printf("Result: %s%n", result >= 60 ? "PASS" : "FAIL");
    }
}

The varargs parameter double... scores lets the method accept any number of scores, and the enhanced for loop over an array is the form to reach for whenever you need every element of a collection or array.

12. Compile-time errors you will meet this week

The compiler reports errors with a file name, a line number, and a message that names the symbol involved.

MessageMeaningFix
';' expectedA statement is missing its terminating semicolonLook at the end of the reported line
class, interface, enum, or record expectedA stray token such as an extra brace, or a missing braceCheck that every opening brace has a partner
cannot find symbolThe compiler cannot resolve a nameCheck the spelling, the imports, and the package of the type
incompatible types: String cannot be converted to intA String was assigned to an intConvert explicitly with Integer.parseInt
bad operand types for binary operator '+'Two incompatible types were combined with +Convert one side before concatenating
class Greeting is public, should be declared in a file named Greeting.javaThe file name does not match the public classRename the file or the class
duplicate class: GreetingTwo classes with the same name are on the source pathRemove the old copy or rename one
method does not override or implement a method from a supertypeThe @Override annotation marks a method that overrides nothingCorrect the signature or remove the annotation
unreachable statementA statement follows a return or a throwDelete the dead code
cannot find or load main classThe runtime could not find the class on the class pathCheck -cp and the fully qualified class name

The last row is a runtime error rather than a compile-time one, which is worth noticing: the program compiled perfectly and still failed to start. The two usual causes are a wrong class path and a main method whose signature does not match exactly what the launcher looks for.

13. A debugging routine that works

When a Java program does not behave as expected, work through the layers in order.

  1. Does it compile? If not, the compiler message names the file and the line. Fix that before anything else.
  2. Does it start? If the launcher reports Could not find or load main class, the class path or the class name is wrong. Print the class path you actually used.
  3. Does it produce the expected output? Compare the output character by character with what you expected, and print intermediate values with printf rather than reasoning about them.
  4. Is the input what you think it is? Print the raw line you read before parsing it. This is where the Scanner newline trap shows up.

With the language basics and the compile-and-run loop in place, the next chapter builds the object model that Java is actually designed around.

javafundamentals

Approach:

The goal of this chapter is not to memorise syntax but to build an accurate mental model of the pipeline, because almost every confusing Java error is a symptom of a wrong model. The pipeline has four stages: the source file, the compiler that turns it into a class file, the class path that decides which classes the runtime can see, and the launcher that finds the entry point and starts executing. Each stage has its own failure mode, and each one is diagnosed with a different command. The approach is to write small programs, run them at each stage, and observe the actual output rather than assuming what happened.

Steps:

  1. Write a single class with a main method in a file named after the class, and compile it with javac Greeting.java. The compiler reports every type error before anything runs.
  2. Run it with java Greeting, then confirm the model by looking at the artefacts: a .class file appears next to the source, and running java Greeting from another directory with the class path set works.
  3. Redirect the output with javac -d out, and observe that the class file now lives under out mirroring the package structure. This is the moment the relationship between package, directory and class path becomes concrete.
  4. Introduce a package and an import, move the file to the matching directory, and run it with java -cp out com.example.Greeting to see how the fully qualified name and the class path entry fit together.
  5. Pass arguments on the command line and read them from args, converting them explicitly with Integer.parseInt because the launcher only ever hands over strings.
  6. Read input with Scanner, and read every value as a line before converting it, so the leftover-newline trap between nextInt and nextLine cannot occur.
  7. Print results with printf and the format specifiers, using %n for the line separator and %.2f for fixed-point numbers.
  8. When something fails, identify the layer first: a compiler message is a source problem, Could not find or load main class is a class path or entry point problem, and wrong output is a logic problem.

Answer:

After this chapter a working Java program has these properties:

  • The source file is named after the public class it contains, and it compiles cleanly with javac, producing a .class file.
  • The class file is platform independent, and the program runs on any machine with a compatible virtual machine, which is the mechanism behind “write once, run anywhere”.
  • The class path entry is the root of the compiled tree, and the class name passed to java includes the package, so javac -d out src/com/example/Greeting.java is followed by java -cp out com.example.Greeting.
  • The entry point is exactly public static void main(String[] args), which is what the launcher looks for, and args receives the command line arguments as strings.
  • Input is read with Scanner, output is produced with printf and the format specifiers, and the newline trap between nextInt and nextLine is avoided by reading lines and parsing them.
  • A failure can be attributed to a layer by the message itself: a compile-time message names a file and a line, ClassNotFoundException names the class path, and NoSuchMethodError or UnsupportedClassVersionError names a mismatch between the compiler and the runtime.

Found an issue with this content?

Tell us what could be improved.