Browse or search our list of 164 Java code samples. Each document is a complete working example annotated with additional explanations and links to relevant resources. For each code sample, a badge indicates the number of annotations accessible through the code.
| Essentials of Java Programming | ||
|---|---|---|
| AnonymousClasses | How to declare anonymous classes, along with typical usage patterns. 21 | anonymous class, lambda expression, final variable, variable capture, local class, implicitly final variable |
| ClassesAndObjects | How to declare classes, explaining what objects are, and how to instantiate them. 21 | class, object state, stateless object, field declaration, access modifier, constructor, this keyword, getter method, new operator |
| EnumTypes | What a enum actually is, and how to declare them, including with additional fields and methods. 13 | enumerated type, constant, Enum class, implicitly declared methods |
| ExceptionHandling | How to declare exceptions, how they propagate through the code, and the difference between checked and unchecked exceptions. 16 | exception, exception handling, exception propagation, try, catch, finally, throw, throws, checked exception, unchecked exception |
| Generics | How to use generic types, how to define your own, and a basic overview of the implications on the types of variables. 18 | generic type, type invocation, type parameter, diamond operator, raw type, type casting, type invocation |
| HelloWorld | The classic "Hello, Word!" program explained in detail. 9 | class, main method, print statement, global variable, public methods, static field, string literal |
| Importing | The different type of import statements with their corresponding effect. Best practices for import statements. 13 | import statement, fully-qualified name, wildcard import, packages, classpath, implicit import, static import |
| Methods | How to declare instance and static methods, and the differences between them. 15 | private field, naming convention, instance method, static method, this keyword, formal parameter, argument, explicit parameter, implicit parameter, return type |
| Types | An overview of primitive vs. references types and why the difference matters. 12 | primitive type, reference type, int, autoboxing, String, array, type conversion, assignment by value, assignment by reference |
| Java Collections Framework | ||
| Lists/ComparingLists | How to check whether two lists are equal. 4 | list, comparing, equality |
| Lists/CopyingLists | How to make a shallow copy of a list in Java. 10 | list, copying |
| Lists/FindingElements | Different ways to find an element in a list in Java. 11 | list, index, equality, binary search, stream, predicate, optional type |
| Lists/HandlingNulls | The different ways to detect and remove null values from lists in Java. 10 | list, null, iterator, removing element |
| Lists/Implementations | An overview of the different implementations of interface List offered by the JDK. 7 | list, array, linked list, concurrency |
| Lists/InitializingLists | The many different ways to initialize a list in Java, with technical explanations and their pros and cons. 20 | list, initialization, double-brace initialization, instance initializer block, varargs, array-back list, List factory method |
| Lists/JoiningLists | How to make join, or merge, two lists. 5 | list, joining, merging |
| Lists/ListIntersection | How to subtract one list from another, that is, to compute the difference or intersection between two lists. 5 | list, joining, merging |
| Lists/RemovingDuplicates | How to remove duplicates from a list in Java. 11 | list, equality, duplicate, set, order |
| Lists/ReorderingLists | How to reorder the elements in a list in Java, including reversing, shuffling, and sorting. 15 | list, ordering, sorting, shuffling, reversing, interface Comparator, interface Comparable, natural ordering |
| Lists/SlicingLists | How to obtain a well-defined part of a list in Java. 10 | list, slicing, sublist, tail, end, array, copying |
| Lists/TraversingLists | The different ways to iterate through the elements in a list in Java. 12 | list, iteration, enhanced for loop, for-each loop, stream, iterator, enumeration |
| Maps/BasicOperations | The basic operations available on a Map, and how to use them. 6 | map, put, get, putIfAbsent |
| Maps/CopyingMaps | The many different ways to copies two map objects by copying all their entries. 7 | map, object copying |
| Maps/Implementations | An overview of the different implementations of interface Map offered by the JDK. 23 | Map, HashMap, LinkedHashMap, SortedMap, TreeMap, EnumMap, SequencedMap, IdentityHashMap, WeakHashMap, ConcurrentHashMap |
| Maps/InitializingMaps | The many different ways to initialize a map in Java, with technical explanations and their pros and cons. 30 | map, initialization, double-brace initialization, instance initializer block |
| Maps/MapAlgebra | How to easily implement different high-level operation involving maps using the bulk operation methods on collections. 3 | map, containAll, removeAll, retainAll |
| Maps/UpdatingMaps | The many different ways to update a map. 13 | map, update |
| Sets/ArrayToSet | Different ways to convert an array to a set in Java. 6 | set, array |
| Sets/Implementations | An overview of the different implementations of interface Set offered by the JDK. 11 | set, sorted set |
| Sets/InitializingSets | The many different ways to initialize a set in Java, with technical explanations and their pros and cons. 20 | sets, initialization, double-brace initialization, instance initializer block, varargs, Set factory method |
| Sets/UsingEnumSet | What an EnumSet is and how to use one. 8 | set, enum, enumerated type |
| Sets/UsingLinkedHashSet | The features and behavior of the LinkedHashSet, a Set implementation that is also a sequence. 7 | set, sequence |
| Sets/UsingTreeSet | The features and behavior of the TreeSet, a Set implementation that is also a navigable sequence with a defined order. 13 | set, sequence, order |
| Introduction to Software Design | ||
| Chapter 1: Introduction/TwelveDays | Sample program that outputs the text of the poem "The Twelve Days of Christmas" to the console. 10 | main method, Java library method, method parameter, recursion |
| Chapter 2: Encapsulation/Card | Class representing a playing card and illustrating best practices for encapsulation in Java. The class creates immutable objects. 21 | abstraction, encapsulation, information hiding, design by contract, Primitive Obsession antipattern, private members, immutability, assert statements |
| Chapter 2: Encapsulation/Deck | Class representing a deck of playing card and illustrating best practices for encapsulation of mutable objects in Java, including how to avoid reference leaks. 16 | mutable field, assert statement, escaping reference, unmodifiableList |
| Chapter 2: Encapsulation/Rank | An enumerated type that represents the rank of a playing card. 7 | enumerated type, Primitive Obsession antipattern, uniqueness |
| Chapter 2: Encapsulation/Suit | An enumerated type that represents the suit of a playing card. 7 | enumerated types, Primitive Obsession antipattern, uniqueness |
| Chapter 3: Types and Interfaces/Card | Class representing a playing card and illustrating effective use of interfaces and polymorphism. 7 | interface Comparable, interface Comparator, implicit declaration, Design by Contract, anonymous class |
| Chapter 3: Types and Interfaces/CardSource | Example of an interface with explanation of polymorphism. 5 | interface, polymorphism, implicitly public |
| Chapter 3: Types and Interfaces/Client | Sample code that uses classes. | list, static method |
| Chapter 3: Types and Interfaces/Deck | Class representing a deck of playing card and illustrating iterable data structures and comparable behavior. 10 | interface Iterable, iteration, iterator, Design by Contract, interface Comparator, function object |
| Chapter 3: Types and Interfaces/Rank | An enumerated type that represents the rank of a playing card. 1 | enumerated type |
| Chapter 3: Types and Interfaces/Suit | An enumerated type that represents the suit of a playing card. 1 | enumerated type |
| Chapter 4: Object State/Card | Class representing a playing card and illustrating an application of the Flyweight pattern. 8 | Flyweight Pattern, enum map, greedy initialization, lazy initialization, static initialization block, private constructor |
| Chapter 4: Object State/CardSource | Interface with illustration of the Null Object pattern with a default method. 7 | interface, polymorphism, implicitly constant, anonymous class, Null Object pattern, default method |
| Chapter 4: Object State/Client | Interface with illustration of the Null Object pattern with a default method. 3 | Null Object pattern, inner classes |
| Chapter 4: Object State/Deck | Class representing a deck of playing card and making use of the static factory methods, nested classes, and final fields. 15 | final field, nested class, inner class, static class, factory method |
| Chapter 4: Object State/GameModel | Application of the Singleton pattern. 3 | Singleton pattern, private constructor |
| Chapter 4: Object State/Rank | An enumerated type that represents the rank of a playing card. | enumerated type |
| Chapter 4: Object State/Suit | An enumerated type that represents the suit of a playing card. | enumerated type |
| Chapter 5: Unit Testing/AbsTest | Sample JUnit5 test class for testing the method Math.abs() 7 | @Test annotation, unit test, naming convention, assertEquals, assert statement |
| Chapter 5: Unit Testing/Card | Class representing a playing card and provided as a dependency for the test code. | |
| Chapter 5: Unit Testing/FoundationPile | Sample class under test. | |
| Chapter 5: Unit Testing/GameModel | Sample class under test. | |
| Chapter 5: Unit Testing/GameModelView | Dependency of the sample class under test GameModel. Provided here just to make the code compile. | |
| Chapter 5: Unit Testing/MetaprogrammingSamples | Common usage patterns for the Java reflection API, an application of the concept of metaprogramming. 6 | class Class, type wildcard, unknown type, metaprogramming, Java reflection, class literal, bounded wildcard |
| Chapter 5: Unit Testing/Move | Dependencies of the sample class under test GameModel. Provided here just to make the code compile. | |
| Chapter 5: Unit Testing/PlayingStrategy | Dependencies of the sample class under test GameModel. Provided here just to make the code compile. | |
| Chapter 5: Unit Testing/Rank | An enumerated type that represents the rank of a playing card. | enumerated type |
| Chapter 5: Unit Testing/Suit | An enumerated type that represents the suit of a playing card. | enumerated type |
| Chapter 5: Unit Testing/TestFoundationPile | Sample test class for the production class FoundationPile, illustrating the use of scaffolding and various testing patterns. 10 | scaffolding, test instance lifecycle, JUnit5, @Test annotation, helper method, test fixture, encapsulation, assertThrows, try/fail pattern |
| Chapter 5: Unit Testing/TestGameModel | Sample test class for the production class GameModel, illustrating testing with stubs. 3 | JUnit5, @Test annotation, test stub |
| Chapter 6: Composition/Card | Class representing a playing card and provided as a dependency for the rest of the code in this chapter. | |
| Chapter 6: Composition/CardSource | Example of an interface that includes polymorphic copying. 1 | interface, polymorphic copying |
| Chapter 6: Composition/CardStack | Wrapper around a list, provided as a dependency to the other code in this chapter. | |
| Chapter 6: Composition/Command | Interface that is the main solution element of the Command design pattern. 3 | Command pattern, class Optional |
| Chapter 6: Composition/CompositeCardSource | A CardSource implementation that represents an aggregation of zero or more card sources. Application of the Composite design pattern. 5 | Composite pattern, vararg, assert statement, polymorphic copying |
| Chapter 6: Composition/Deck | Class representing a deck of playing card and illustrating the concept of an instance command factory method. 4 | polymorphic copying, anonymous class, factory method, optional type |
| Chapter 6: Composition/GameModel | Stub of a class that represents the state of a card game. Illustrates the use of the Prototype design pattern. 2 | Prototype pattern, polymorphic copying, @SuppressWarning |
| Chapter 6: Composition/LoggingDeck | Illustrates composition within a type hierarchy. | interface implementation, object aggregation, delegation |
| Chapter 6: Composition/LoggingDecorator | Application of the Decorator design pattern. 4 | Decorator pattern, delegation |
| Chapter 6: Composition/MemorizingDecorator | Application of the Decorator design pattern. 1 | Decorator pattern, delegation |
| Chapter 6: Composition/Rank | An enumerated type that represents the rank of a playing card. | enumerated type |
| Chapter 6: Composition/Suit | An enumerated type that represents the suit of a playing card. | enumerated type |
| Chapter 7: Inheritance/AbstractDecorator | An abstract class for classes that serve as decorators in the Decorator design pattern. 5 | abstract class, Decorator pattern, protected visibility, protected constructor |
| Chapter 7: Inheritance/AbstractMove | An abstract class that illustrates an application of the Template Method design pattern. 10 | abstract class, abstract method, protected visibility, Template Method pattern |
| Chapter 7: Inheritance/Card | Class representing a playing card and provided as a dependency for the rest of the code in this chapter. | |
| Chapter 7: Inheritance/CardMove | Sample concrete class that extends an abstract class and plays a role in the Template Method design pattern. 2 | final class, Template Method pattern |
| Chapter 7: Inheritance/CardSource | Interface provided as a dependency for the rest of the code in this chapter. | |
| Chapter 7: Inheritance/CardStack | Wrapper around a list, provided as a dependency to the other code in this chapter. | |
| Chapter 7: Inheritance/Deck | Class representing a deck of playing card and provided as a dependency for the other classes in this topic. | |
| Chapter 7: Inheritance/GameModel | Stub class to represent a client of the Move class hierarchy. | |
| Chapter 7: Inheritance/LoggingDecorator | Example of a decorator that prints call events to the console. 1 | super calls, Decorator pattern, inheritance |
| Chapter 7: Inheritance/MemorizingDeck | Example of inheritance with method overriding and super calls. 5 | inheritance, overriding, super call, field initialization, polymorphic copying |
| Chapter 7: Inheritance/Move | Interface provided as dependency for other code in the chapter. | |
| Chapter 7: Inheritance/Rank | An enumerated type that represents the rank of a playing card. | enumerated type |
| Chapter 7: Inheritance/Suit | An enumerated type that represents the suit of a playing card. | enumerated type |
| Chapter 8: Inversion of Control/AbstractCardSourceVisitor | An abstract class for classes that implements the Visitor interface. 1 | abstract class, Visitor pattern |
| Chapter 8: Inversion of Control/AceDetector | A sample concrete observer in the Observer design pattern. 1 | Observer pattern, concrete observer, callback |
| Chapter 8: Inversion of Control/Card | Class representing a playing card and provided as a dependency for the rest of the code in this chapter. | |
| Chapter 8: Inversion of Control/CardSequence | Wrapper around a list of cards and provided as a dependency for the rest of the code in this chapter. | |
| Chapter 8: Inversion of Control/CardSource | An interface enhanced to support integration with the Visitor design pattern. 1 | Visitor pattern, accept method |
| Chapter 8: Inversion of Control/CardSourceVisitor | An interface defining an abstract visitor in the Visitor design pattern. 1 | Visitor pattern, accept method |
| Chapter 8: Inversion of Control/CardStack | Wrapper around a list of cards and provided as a dependency for the rest of the code in this chapter. | |
| Chapter 8: Inversion of Control/CardStackObserver | An interface defining the abstract observer in the Observer design pattern. 2 | Observer pattern, callback method, adapter class, push data-flow |
| Chapter 8: Inversion of Control/ChecksContainmentVisitor | Concrete visitor implementation that accumulates state during traversal. 11 | Visitor pattern, object state, accept method, visit method, data flow |
| Chapter 8: Inversion of Control/CompositeCardSource | Composite object that defines a structure that can be traversed by a visitor in the Visitor design pattern. | |
| Chapter 8: Inversion of Control/Counter | Example of a concrete observer in the Observer design pattern. | Observer pattern, concrete observer |
| Chapter 8: Inversion of Control/CountingVisitor | Example of a concrete stateful visitor in the Visitor design pattern. | Visitor pattern |
| Chapter 8: Inversion of Control/Deck | Class representing a deck of playing card and provided as a dependency for the other classes in this topic. | |
| Chapter 8: Inversion of Control/Driver | Example code for creating and using different kinds of visitors in the Visitor design pattern. 5 | Visitor pattern |
| Chapter 8: Inversion of Control/GenericVisitorSample | Sample application of the Visitor design pattern using generic types instead of state accumulation. | Visitor pattern, generic type |
| Chapter 8: Inversion of Control/LuckyNumber | Small GUI application illustrating the Observer pattern as well as GUI programming with JavaFX. 26 | Observer pattern, JavaFX, application class, grid, GUI components, event, event handler, observer registration, observer notification |
| Chapter 8: Inversion of Control/ObservableCardStack | A stack of card objects whose state changes can be observed in accordance with the Observer design pattern. 4 | Observer pattern, inheritance |
| Chapter 8: Inversion of Control/PrintVisitor | A simple example of a concrete visitor in the Visitor design pattern. | Visitor pattern |
| Chapter 8: Inversion of Control/Rank | An enumerated type that represents the rank of a playing card. | enumerated type |
| Chapter 8: Inversion of Control/StructurePrinterVisitor | A simple example of a concrete visitor in the Visitor design pattern, which prints out the object hierarchy it traverses, using indentation to show nesting. | Visitor pattern, object composition |
| Chapter 8: Inversion of Control/Suit | An enumerated type that represents the suit of a playing card. | enumerated type |
| Chapter 9: Functional Design/AutoPlayer | Strategy design pattern applied using functional-style design. 2 | Strategy pattern, functional programming |
| Chapter 9: Functional Design/Card | Implementation of a playing card with factory functions to create Comparators using functional-style programming. 12 | interface Comparable, functional programming, factory method, lambda expression |
| Chapter 9: Functional Design/CardSelectionStrategy | Example of a user-defined functional interface. 1 | functional interface |
| Chapter 9: Functional Design/CardSource | An interface used in other code samples in this chapter. | |
| Chapter 9: Functional Design/CardStack | Wrapper around a list of cards and provided as a dependency for the rest of the code in this chapter. | |
| Chapter 9: Functional Design/CardUtils | Code to demonstrate how to use references to static methods. | |
| Chapter 9: Functional Design/ConsumingDecorator | An example of using the Consumer interface | interface Consuming, Decorator pattern |
| Chapter 9: Functional Design/Deck | A class representing a deck of cards with a method to stream all the cards in the deck. 1 | interface Stream |
| Chapter 9: Functional Design/Filter | Examples of a user-defined functional interface. | |
| Chapter 9: Functional Design/InfiniteCardSource | Demonstrates how to use the Supplier interface to obtain card in the context of a card source that can supply an infinity of cards. 2 | interface Supplier |
| Chapter 9: Functional Design/ObservableDeck | Sample observable object where the Observer design pattern is applied using functional-style design. 2 | Observer pattern, functional programming, interface Consumer, functional interface |
| Chapter 9: Functional Design/Rank | An enumerated type that represents the rank of a playing card. | enumerated type |
| Chapter 9: Functional Design/Samples | Numerous small samples of functional programming in action. | functional programming, lambda expression, method reference, functional interface, stream |
| Chapter 9: Functional Design/Suit | An enumerated type that represents the suit of a playing card. | enumerated type |
| Solutions 1: Introduction/Exercise01 | Sample program that outputs the text of the poem "The Twelve Days of Christmas" to the console and demonstrates recursion vs. iteration. 2 | twelve days of Christmas, iteration, recursion |
| Solutions 1: Introduction/Exercise02 | Sample program that outputs the text of the poem "The Twelve Days of Christmas" to the console and demonstrates how to parameterize a program. 7 | twelve days of Christmas, command-line argument, |
| Solutions 1: Introduction/Exercise03 | Sample program that outputs the text of the poem "The Twelve Days of Christmas" to the console and demonstrates how to parameterize a program with multiple arguments. 5 | twelve days of Christmas, command-line argument, |
| Solutions 1: Introduction/Exercise04 | Sample program that outputs the text of the poem "The Twelve Days of Christmas" to the console and demonstrates how to localize a program with resource bundles. 8 | twelve days of Christmas, command-line argument, resource bundle, localization |
| Solutions 2: Encapsulation/Exercise01 | Representing an int value using Booleans and why this is not a good idea. 5 | types, Boolean |
| Solutions 2: Encapsulation/Exercise02 | Representing a playing card as an enumerated type. 1 | enumerated type |
| Solutions 2: Encapsulation/Exercise03 | Adding a method with randomness to a class. 3 | class design |
| Solutions 2: Encapsulation/Exercise04 | Adding a method to an enum in Java. 2 | enumerated type |
| Solutions 2: Encapsulation/Exercise05 | Code using proper abstractions to work with playing card data. 2 | primitive obsession, refactorings |
| Solutions 2: Encapsulation/Exercise06 | Code to implement a sequence based on values of enumerated types. 1 | circular sequence, enum method |
| Solutions 2: Encapsulation/Exercise07 | Code to implement a playing card that can be a joker. 6 | nullability |
| Solutions 2: Encapsulation/Exercise08 | Code to implement a playing card that can be a joker of different kinds. 9 | enumerated types |
| Solutions 2: Encapsulation/Exercise09 | Sample demonstrating how to implement a copy constructor | copy constructor |
| Solutions 2: Encapsulation/Exercise10 | Sample demonstrating how to implement a copy constructor on an aggregate object. 3 | object aggregation, copy constructor |
| Solutions 2: Encapsulation/Exercise11 | Empty sample. | object diagram |
| Solutions 2: Encapsulation/Exercise12 | Sample demonstrating how to use enumerated types 5 | enumerated type |
| Solutions 3: Types and Interfaces/Exercise01To03 | A well-encapsulated class representing a hand (collection) of cards. 11 | interface implementation, anonymous class, iterator |
| Solutions 3: Types and Interfaces/Exercise04 | Diagram only. | class diagram |
| Solutions 3: Types and Interfaces/Exercise06 | Example of a stateful comparator (not recommended). 1 | Comparator |
| Solutions 3: Types and Interfaces/Exercise08 | Diagram only. | class diagram |
| Solutions 3: Types and Interfaces/Exercise09 | Example of dependency injection. 3 | dependency injection, comparable, iterable |
| Solutions 3: Types and Interfaces/Exercise10 | Diagram only. | class diagram |
| Solutions 3: Types and Interfaces/Exercise11 | Diagram only. | class diagram |
| Solutions 4: Object State/Exercise01 | Diagram only. | state diagram |
| Solutions 4: Object State/Exercise02 | Diagram only. | state diagram |
| Solutions 4: Object State/Exercise03 | How to use optionals in Java. 5 | encapsulation, optional types |
| Solutions 4: Object State/Exercise04 | How to use the null design pattern in Java. 3 | null object design pattern |
| Solutions 4: Object State/Exercise05 | How to use the null design pattern in Java. 1 | null object design pattern, interface |
| Solutions 4: Object State/Exercise06 | How to implement the equals method in Java. 6 | equals method |
| Solutions 4: Object State/Exercise07 | How to apply the flyweight pattern with pre-initialization of the values. 5 | Flyweight design pattern, map interface |
| Solutions 4: Object State/Exercise08 | How to apply the flyweight pattern with lazy initialization of the values. 3 | Flyweight design pattern, map interface |
| Solutions 4: Object State/Exercise09 | How to apply the Singleton design. 3 | Singleton design pattern |
| Solutions 5: Unit Testing/Exercise01 | Sample unit tests for the method Math.min. 3 | unit testing |
| Solutions 5: Unit Testing/Exercise02 | Sample unit tests for the method Math.cos. 7 | unit testing, floating-point arithmetics, trigonometry |
| Solutions 5: Unit Testing/Exercise03 | Sample unit tests for the method String#concat. 1 | unit testing, equality, string |
| Solutions 5: Unit Testing/Exercise04 | Object diagram of an object graph that involves Java reflection. | metaprogramming, object diagram |
| Solutions 5: Unit Testing/Exercise05 | Program that takes two command-line arguments: the short name of a subtype of type Number and a number literal, and that creates a new instance of that type that represents the number 5 | metaprogramming, reflection, numbers |
| Solutions 5: Unit Testing/Exercise06 | Program to verify whether it is possible to call any parameterless method of class String on an empty string without raising an exception. 2 | metaprogramming, reflection, string |
| Solutions 5: Unit Testing/Exercise07 | Program to verify whether it is possible to call any parameterless method of class String on an empty string without raising an exception. 4 | unit testing, stack, test fixture |
| Solutions 5: Unit Testing/Exercise08to10 | Unit tests for private members 1 | unit testing, private members |
| Solutions 5: Unit Testing/Exercise11 | Unit tests demonstrating the use of stubs. 2 | unit testing, stubs |