Java's Bigger Picture: Objects, Data, and Handling the Unexpected
You already know how to write classes and methods. This chapter takes a quick tour of the tools Java gives you once those basics are in place.
Everything is an Object
In Java, every class is part of one big family. The root of the family tree is a class called Object. It is the built-in class that all other classes inherit from, directly or indirectly. That's why you can store any object in a variable of type Object, and why every object comes with shared methods like toString(), which turns it into readable text.
An important detail: a variable does not hold the object itself. It holds a reference — like a price tag pointing to a shelf item. Two variables can point to the same object. When nothing points to an object anymore, Java quietly clears it away. This automatic cleanup is called garbage collection.
Enums, Records, and Exceptions
- An enum is a type with a fixed list of values, like
Day.MONDAY. Use it when a value can only be one of a few choices. - A record is a short way to define a class that just holds data, like
record Point(int x, int y) {}. - An exception is Java's way of reporting a problem at runtime, such as a missing file. You catch exceptions to handle them gracefully instead of crashing.
Collections, Generics, and Files
- The collections framework is a set of ready-made containers:
List(ordered items),Set(no duplicates), andMap(key-to-value pairs). - Generics let you say what type goes inside:
List<String>is a list that only holds strings. The compiler checks this for you. - Files are read and written with classes from the
java.nio.filepackage.
Lambdas, Streams, and Concurrency
A lambda is a short, nameless function, like x -> x * 2. A stream is a pipeline that sends data through steps — filter it, transform it, collect it. Concurrency means doing several things at once using threads, usually managed for you by an executor service, which is a helper that runs tasks on a pool of worker threads.
caption: How these Java features build on objects
alt: A flow chart showing objects feeding into enums, records, and exceptions; generics feeding collections; collections and lambdas feeding streams; exceptions feeding files and concurrency.
Exercise
Why does Java garbage-collect objects automatically?
Show answer
Because when no references point to an object anymore, it can never be used again, so Java frees its memory for you without you having to delete it manually.
Spotted a mistake, or code that does not work?