Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

The Programming Shortcut: Java

Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about null and exceptions.

Java got small while nobody was looking

Java has a reputation. Ask around and you’ll hear about public static void main, classes named AbstractSingletonProxyFactoryBean, and build files longer than the program they build. Some of that was earned, twenty years ago.

Here is a complete Java program today:

void main() {
    IO.println("Hello");
}

That’s it. No class to declare, nothing to import, no build tool. Save it in a file and run it.

Meanwhile, Java became the language a large share of the world’s servers run on: banks, airlines, shops, the back ends of apps on your phone. It stayed there by rarely breaking old code, which is why Java’s oldest design decisions are alive and well in a language that otherwise feels modern.

Two of those decisions are what this article is about. They are Java’s answers to two questions every program has to answer, over and over: what if the value I need isn’t there? and what if the thing I asked for couldn’t be done?

Java answers the first with null and the second with exceptions. Neither answer shows up in the types the way you might expect. So Java is a fine place to learn what programming without a safety net is like, and the habits that let you do it well anyway. Those habits travel to Python, JavaScript, and anywhere else a value might quietly be missing.

What you can skip

You already know most of what a Java program is made of. The interesting rows are the first two, and they’re where the rest of this article lives.

What you knowluxJava
a value that might be missingOptionany object can be null; Optional by convention
an operation that might failResultexceptions, some of them checked
a structstructrecord
functions, loops, if, arraysthe same ideasthe same ideas, in C-style braces

If you learned lux, those first two rows are the story in miniature. lux’s Option and Result were a safety net: the type itself said “this might be missing” or “this might fail”, and match wouldn’t let you ignore it. Java has no such net under most of its code. What it has instead is a set of habits, and the habits are worth more than any one language’s syntax.

Edit, then java Main.java

You need a Java Development Kit (JDK), version 25 or later. The free builds at adoptium.net install like any other program. When java -version prints 25 or higher, you’re set.

Make a folder, and in it a file called Main.java:

void main() {
    String name = "Java";
    IO.println("Hello from " + name + " " + Runtime.version().feature());
}

Then run it:

java Main.java
Hello from Java 25

Everything in this article runs that way: edit Main.java, save, run java Main.java. The java command compiles your file in memory, checks it, and runs it, all in one step. A file written this way, with no class around it, is called a compact source file. Java treats it as a class it writes for you, and it brings the standard library’s everyday parts (lists, maps, files) into scope without any import lines. IO.println prints a line.

Keep that terminal open. Every snippet below is a whole program you can paste over Main.java and run.

Two kinds of bad news

Before any Java, the idea itself.

A program gets bad news in two shapes. Sometimes a value simply isn’t there: you look up a word in a dictionary and it’s not in it; a form field was left blank; a customer has no middle name. Nothing went wrong. Missing is a perfectly normal answer.

Other times an operation couldn’t be done: the file you asked to read doesn’t exist, the text you asked to turn into a number says “seven”, the network went away halfway through. Something did go wrong, and there’s usually a reason worth reporting.

Languages differ in where they put this news.

Some put it in the type. In Rust, a function that might not find something returns an Option, a value that is either “here it is” or “nothing”, and you can’t use what’s inside without first saying what happens when there’s nothing. (The Rust article is the home of Option and its sibling Result, the same idea for failures.) The compiler checks that every caller deals with the bad news, so the net catches you before the program ever runs.

Java puts most of it outside the type. A missing value is null, a special value that any object variable can hold. A failure is an exception, which leaves the normal flow of your program entirely. The types in your code mostly don’t mention either, and the compiler mostly doesn’t check.

That’s the safety net gone. Let’s see what falls through it, and then what careful Java programmers do about it.

Null: the value that isn’t one

In Java, variables come in two kinds. The primitive types, such as int, double and boolean, hold their value directly, and they can never be null. An int is always some number. Everything else is a reference type: a String, a List, a Map, your own records. A variable of a reference type holds a reference to an object somewhere in memory, the way a phone number refers to a phone. And any reference can be null, meaning it refers to nothing at all.

So a variable declared as String holds either a string or null. The type doesn’t say which, and the compiler doesn’t ask.

Where do nulls come from? Mostly from code that needs a way to say “not found”. Java’s Map (a dictionary: keys in, values out) is the classic source. Ask it for a key it doesn’t have, and it hands you null:

void main() {
    Map<String, String> capitals = new HashMap<>();
    capitals.put("France", "Paris");
    capitals.put("Japan", "Tokyo");

    String capital = capitals.get("Peru");
    IO.println("Peru's capital has " + capital.length() + " letters");
}

(The <String, String> part says the map’s keys and values are both strings. Java calls that generics, and the Swift article is where the series explains them. Here you can read it as a label.)

This compiles without a murmur. Then it runs, and stops:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "<local2>" is null
	at Main.main(Main.java:7)

A NullPointerException, known to every Java programmer as an NPE, is what happens when you treat null as if it were an object: call a method on it, read a field from it. Modern Java tells you which value was null and on which line, which is more help than it used to give. (<local2> is your variable capital. When java compiles a file on the fly, it numbers local variables instead of keeping their names.)

Notice where the program stopped. Not at get, where the missing value came from, but at length(), where it was used. In this snippet those are one line apart. In a real program they can be in different files, written by different people, run minutes apart.

Null travels

That gap between where a null is born and where it bites is the real trouble with null. Here it is stretched out a little:

record Contact(String name, String email) {}

String domainOf(Contact contact) {
    String email = contact.email();
    return email.substring(email.indexOf('@') + 1);
}

void main() {
    List<Contact> contacts = List.of(
            new Contact("Ana", "ana@example.com"),
            new Contact("Ben", null),
            new Contact("Cy", "cy@example.org"));

    for (Contact contact : contacts) {
        IO.println(contact.name() + " is at " + domainOf(contact));
    }
}
Ana is at example.com
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.indexOf(int)" because "<local2>" is null
	at Main.domainOf(Main.java:5)
	at Main.main(Main.java:15)

Ben was created with no email on line 11. Nothing complained. The record held the null, the list held the record, the loop handed it to domainOf, and only there, inside a function that was written correctly, did the program fall over. The error points at domainOf, but domainOf isn’t where the mistake is.

That’s why Tony Hoare, who added null references to a language called ALGOL W in 1965, later called them his “billion-dollar mistake”. The problem isn’t that a value can be missing. Missing values are real. The problem is that the missing value looks just like a present one until the moment you touch it.

Habit one: decide at the door

The first habit is to deal with null where it enters your program, and nowhere else. Every value comes in through some door: a map lookup, a file, a user’s answer, another library. Right there, decide what missing means. Use a default, skip the item, report a problem. Then everything past the door can trust its values.

For a map, the door is the lookup itself, and Map has a method built for it:

void main() {
    Map<String, Integer> stock = Map.of("apples", 12, "pears", 0);

    for (String fruit : List.of("apples", "pears", "plums")) {
        int count = stock.getOrDefault(fruit, 0);
        IO.println(fruit + ": " + count);
    }
}
apples: 12
pears: 0
plums: 0

getOrDefault answers the “what if it’s missing?” question on the spot, so count is a plain int, and an int can never be null.

Habit two: fail at the door

Sometimes missing isn’t a normal answer. A contact with no email might simply be a bug. Then you want the program to stop, but at the door, where the bug is, not three functions later.

Java’s Objects.requireNonNull does that. It hands back its argument if it isn’t null, and throws an NPE straight away if it is. Records let you run a check like this every time one is made, in a compact constructor: a block named after the record that runs before the fields are filled in.

record Contact(String name, String email) {
    Contact {
        Objects.requireNonNull(email, "email is required");
    }
}

void main() {
    var ana = new Contact("Ana", "ana@example.com");
    IO.println(ana);
    var ben = new Contact("Ben", null);
    IO.println(ben);
}
Contact[name=Ana, email=ana@example.com]
Exception in thread "main" java.lang.NullPointerException: email is required
	at java.base/java.util.Objects.requireNonNull(Objects.java:246)
	at Main$Contact.<init>(Main.java:3)
	at Main.main(Main.java:10)

Same crash, much better place. Line 10 is the line that made Ben, so the error now points at the cause instead of an innocent bystander. This is called failing fast, and it turns a mystery into a typo.

Habit three: say “maybe” out loud

The third habit is for functions you write. If your function might have nothing to return, don’t return null and hope the caller remembers. Return an Optional.

Optional<String> is a box that either holds a string or is empty, and Java has had it since version 8. If you’ve used an Option or Maybe type, this is Java’s version. The difference is that nothing forces anyone to use it. It’s a convention, and Java’s own documentation says what it’s for: a method’s return type, where there may be “no result” and a null would likely cause errors.

Map<String, String> capitals = Map.of("France", "Paris", "Japan", "Tokyo");

Optional<String> capitalOf(String country) {
    return Optional.ofNullable(capitals.get(country));
}

void main() {
    for (String country : List.of("France", "Peru")) {
        String answer = capitalOf(country)
                .map(city -> city + " (" + city.length() + " letters)")
                .orElse("not in my list");
        IO.println(country + ": " + answer);
    }
}
France: Paris (5 letters)
Peru: not in my list

Optional.ofNullable is a door: it turns a possible null into a box that might be empty. map works on what’s inside if there’s anything there (the city -> ... part is a small unnamed function, a lambda). orElse says what to use when the box is empty. Nowhere in that chain can you call .length() on nothing.

The methods are handy, but the return type matters more. A caller who reads Optional<String> capitalOf(String country) knows, before running anything, that the answer might be missing. A String return type can’t tell them that.

Exceptions: bad news that leaves the room

Now the other kind of bad news: the operation that couldn’t be done.

What should a function that turns text into a number do when the text is “seven”? In lux, parseInt returns an Option, and the caller matches on it. Java’s Integer.parseInt returns a plain int. And there is no int that means “that wasn’t a number”. So it does something else:

void main() {
    int age = Integer.parseInt("seven");
    IO.println("Next year you'll be " + (age + 1));
}
Exception in thread "main" java.lang.NumberFormatException: For input string: "seven"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
	at java.base/java.lang.Integer.parseInt(Integer.java:565)
	at java.base/java.lang.Integer.parseInt(Integer.java:662)
	at Main.main(Main.java:2)

It throws an exception. An exception is an object that describes what went wrong, and throwing it means abandoning the current function right there. No return value, no next line. Java leaves that function, then the function that called it, then the one that called that, until it finds code that has said “I can handle this kind of problem”. If it never finds any, the program ends and prints the list you see above, called a stack trace: every function that was in the middle of running, innermost first. Read it from the top until you reach your own code. Main.java:2 is the line to look at.

Code that handles an exception catches it, with try and catch:

int readAge(String text) {
    return Integer.parseInt(text.strip());
}

int ageNextYear(String text) {
    return readAge(text) + 1;
}

void main() {
    for (String answer : List.of("41", " 29 ", "seven")) {
        try {
            IO.println(answer + " -> " + ageNextYear(answer));
        } catch (NumberFormatException e) {
            IO.println(answer + " -> not an age: " + e.getMessage());
        }
    }
}
41 -> 42
 29  -> 30
seven -> not an age: For input string: "seven"

Look at ageNextYear. It calls readAge, which can fail, and it does nothing about it. It doesn’t need to. When “seven” comes along, the exception flies out of parseInt, out of readAge, out of ageNextYear, and lands in the catch in main. The functions in between never knew.

This cuts both ways. The good side: code in the middle stays clean. It deals with the normal case and lets failures pass through to whoever is in a position to do something about them. The other side: looking at ageNextYear, you can’t tell that it might not return at all. The failure is invisible in its type, just like null was.

Habit four: catch where you can act

That suggests the fourth habit. Catch an exception in the place that knows what to do about it, not in the place where it happened.

readAge can’t do anything useful with “seven”. It doesn’t know whether to ask again, use a default or give up, because it doesn’t know who’s asking. main knows. It’s printing answers, so it can print “not an age” and carry on with the next one. A good catch is close to a decision: skip this line, try again, tell the user, use the backup. If you can’t name the decision, you’re in the wrong place to catch.

The part of the net Java kept

All of that is true of the exceptions you’ve seen so far, which Java calls unchecked. But Java has a second kind, and here the compiler does step in.

Reading a file can fail for reasons no amount of careful coding prevents: the file was deleted, the disk is full, you don’t have permission. Java’s designers decided failures like these should be impossible to forget, so they made them checked exceptions. If a method can throw one, its signature says so, with the word throws. And any code that calls it must either catch the exception or declare it too, passing the news upward on purpose.

Files.readString reads a whole file into a string, and it’s declared throws IOException. Call it without saying what happens on failure:

void main() {
    String notes = Files.readString(Path.of("notes.txt"));
    IO.println(notes);
}
Main.java:2: error: unreported exception IOException; must be caught or declared to be thrown
    String notes = Files.readString(Path.of("notes.txt"));
                                   ^
1 error
error: compilation failed

This time nothing ran. The compiler refused, just like a language with a Result type would. Make the decision, and it’s happy:

void main() {
    try {
        String notes = Files.readString(Path.of("notes.txt"));
        IO.println(notes);
    } catch (IOException e) {
        IO.println("No notes yet (" + e + ")");
    }
}
No notes yet (java.nio.file.NoSuchFileException: notes.txt)

The catch caught a NoSuchFileException, though it asked for an IOException. Exceptions come in families, and catching a family catches all its members. (NumberFormatException belongs to a family called RuntimeException, which is what makes it unchecked.)

So Java’s net has one strand left: the failures that come from the outside world. Everything else, including every null, falls straight through.

Against the grain

If you’re used to a language with Option and Result, Java asks you to give up a guarantee you may not have noticed you were relying on: a type tells the truth. In Java, a String might not be a string, and a method that returns an int might not return at all. The compiler checks that your types fit together. It doesn’t check that the values are there.

Several languages that grew up in Java’s shadow closed that gap. Kotlin, C# and Dart all let you write String? for “a string or null”, and plain String then means a string. Each of them checks, before anything runs, that you dealt with the ? (Kotlin and Dart with errors, C# with warnings). The Kotlin and C# articles touch on it along the way. In Java, the checking is your job, and the four habits are how you do it.

Beware of the empty catch block. Sooner or later the compiler will demand you handle a checked exception you don’t care about, and you’ll be tempted to write this:

try {
    settings = Files.readString(path);
} catch (IOException e) {
}

It compiles, and the error goes away, along with every clue to what happened. settings keeps whatever it held before, quite likely null, and some other line, far away, will throw an NPE about it next week. This is the worst thing you can do with an exception, worse than not catching it at all, because an uncaught exception at least tells you what went wrong and where. If you truly can’t act on it, don’t catch it: add throws IOException to your method and let the news travel up to someone who can. And if you catch it, do something you could describe out loud.

A small project: is there enough for pancakes?

Time to put the habits together. The program reads a list of what’s in your pantry, then checks whether you have enough of everything a recipe needs. The pantry file is the outside world, so it’s where the trouble comes in: the file might be missing, a line might have no amount, an amount might not be a number, and the recipe might ask for something the pantry never mentions.

Make a new folder. In it, save this as pantry.txt, blank line and all:

flour, 500
eggs, 6
milk, about a liter
sugar, 200

butter

And save this as Main.java next to it:

record Need(String item, int amount) {}

List<Need> pancakes = List.of(
        new Need("flour", 200),
        new Need("eggs", 2),
        new Need("milk", 300),
        new Need("butter", 30));

void main() {
    Map<String, Integer> pantry;
    try {
        pantry = readPantry(Path.of("pantry.txt"));
    } catch (IOException e) {
        IO.println("Can't read the pantry: " + e);
        return;
    }

    boolean ready = true;
    IO.println("Pancakes need:");
    for (Need need : pancakes) {
        String verdict = amountOf(pantry, need.item())
                .map(have -> have >= need.amount() ? "ok" : "short by " + (need.amount() - have))
                .orElse("missing");
        IO.println("  " + need.item() + " " + need.amount() + ": " + verdict);
        if (!verdict.equals("ok")) {
            ready = false;
        }
    }
    IO.println(ready ? "Get the pan out." : "Not yet. Time for a shopping list.");
}

Map<String, Integer> readPantry(Path file) throws IOException {
    Map<String, Integer> pantry = new HashMap<>();
    List<String> lines = Files.readAllLines(file);
    for (int i = 0; i < lines.size(); i++) {
        String line = lines.get(i).strip();
        if (line.isEmpty()) {
            continue;
        }
        String[] parts = line.split(",");
        if (parts.length != 2) {
            IO.println("line " + (i + 1) + " skipped: no amount in \"" + line + "\"");
            continue;
        }
        try {
            pantry.put(parts[0].strip(), Integer.parseInt(parts[1].strip()));
        } catch (NumberFormatException e) {
            IO.println("line " + (i + 1) + " skipped: \"" + parts[1].strip() + "\" is not a number");
        }
    }
    return pantry;
}

Optional<Integer> amountOf(Map<String, Integer> pantry, String item) {
    return Optional.ofNullable(pantry.get(item));
}

The file in the series’ repository, projects/java/Main.java, has the same code plus a block of “Try this next…” ideas at the end. Run it from that folder:

java Main.java
line 3 skipped: "about a liter" is not a number
line 6 skipped: no amount in "butter"
Pancakes need:
  flour 200: ok
  eggs 2: ok
  milk 300: missing
  butter 30: missing
Not yet. Time for a shopping list.

Every kind of bad news in the program has one place where it’s handled, and each place makes a decision.

The missing file is a checked exception. readPantry can’t do anything about it, so it declares throws IOException and passes it up. main catches it, because main knows what to do: say so and stop. Try it. Rename pantry.txt and run again.

The line butter has no amount. That’s missing data, not a failure, so it’s handled with a plain if, right where the line is read. The blank line is missing data too, and it’s skipped the same way.

“about a liter” is a failure: parseInt throws. It’s caught inside the loop, because that’s where the decision lives. One bad line shouldn’t cost you the rest of the file, so the loop reports it and moves on.

And the recipe’s lookups go through amountOf, the one door between the map’s nulls and the rest of the program. Its return type, Optional<Integer>, tells main that an item might not be there, and orElse("missing") is where main answers. No variable in main is ever null.

Now edit pantry.txt. Fix the milk line, give the butter an amount, run again. Then break it in a new way of your own and see which door catches it.

What’s left out, and where to go next

You haven’t met finally, or try-with-resources, Java’s way of making sure a file or a connection is closed even when an exception flies past. You haven’t written your own exception classes, or seen how one exception can carry another as its cause. You haven’t met the annotations (such as @Nullable) and outside checkers that some teams use to bolt null checking onto Java. And you’ve skipped almost all of Java itself: classes, interfaces, inheritance, the standard library, concurrency. Those are the language. This article was about one idea.

When you go looking for more, start at dev.java/learn, the learning site run by the Java team at Oracle. Be a little wary of older tutorials that open with Maven, Spring or a ten-line public static void main before you’ve written anything. They aren’t wrong, but they solve problems you don’t have yet, and java Main.java will take you a long way first.

Try this

Java comes with a place to try anything one line at a time. It’s called jshell, and it was installed with your JDK. Type jshell, then /help.

Then bring it this question: what’s the difference between missing and failing? Type Map.of("a", 1).get("b") and see what comes back. Then Integer.parseInt("b"). Then Optional.ofNullable(null). One answers with nothing, one refuses to answer, and one answers with a box that says so. /exit when you’re done.

  • Rust is the home of Option and Result, the safety net this article does without, built into the types.
  • Kotlin, C# and Dart write a value that might be missing as T?, and check it before the program runs.
  • Swift explains generics, the <String, Integer> labels on Java’s maps and lists.

Tested with JDK 25.0.5.1 LTS (Temurin), November 2026.