Code Sample Catalog

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.

Showing 0 of 164 samples (0 excluded)
Essentials of Java Programming
AnonymousClassesHow to declare anonymous classes, along with typical usage patterns. 21anonymous class, lambda expression, final variable, variable capture, local class, implicitly final variable
ClassesAndObjectsHow to declare classes, explaining what objects are, and how to instantiate them. 21class, object state, stateless object, field declaration, access modifier, constructor, this keyword, getter method, new operator
EnumTypesWhat a enum actually is, and how to declare them, including with additional fields and methods. 13enumerated type, constant, Enum class, implicitly declared methods
ExceptionHandlingHow to declare exceptions, how they propagate through the code, and the difference between checked and unchecked exceptions. 16exception, exception handling, exception propagation, try, catch, finally, throw, throws, checked exception, unchecked exception
GenericsHow to use generic types, how to define your own, and a basic overview of the implications on the types of variables. 18generic type, type invocation, type parameter, diamond operator, raw type, type casting, type invocation
HelloWorldThe classic "Hello, Word!" program explained in detail. 9class, main method, print statement, global variable, public methods, static field, string literal
ImportingThe different type of import statements with their corresponding effect. Best practices for import statements. 13import statement, fully-qualified name, wildcard import, packages, classpath, implicit import, static import
MethodsHow to declare instance and static methods, and the differences between them. 15private field, naming convention, instance method, static method, this keyword, formal parameter, argument, explicit parameter, implicit parameter, return type
TypesAn overview of primitive vs. references types and why the difference matters. 12primitive type, reference type, int, autoboxing, String, array, type conversion, assignment by value, assignment by reference
Java Collections Framework
Lists/ComparingListsHow to check whether two lists are equal. 4list, comparing, equality
Lists/CopyingListsHow to make a shallow copy of a list in Java. 10list, copying
Lists/FindingElementsDifferent ways to find an element in a list in Java. 11list, index, equality, binary search, stream, predicate, optional type
Lists/HandlingNullsThe different ways to detect and remove null values from lists in Java. 10list, null, iterator, removing element
Lists/ImplementationsAn overview of the different implementations of interface List offered by the JDK. 7list, array, linked list, concurrency
Lists/InitializingListsThe many different ways to initialize a list in Java, with technical explanations and their pros and cons. 20list, initialization, double-brace initialization, instance initializer block, varargs, array-back list, List factory method
Lists/JoiningListsHow to make join, or merge, two lists. 5list, joining, merging
Lists/ListIntersectionHow to subtract one list from another, that is, to compute the difference or intersection between two lists. 5list, joining, merging
Lists/RemovingDuplicatesHow to remove duplicates from a list in Java. 11list, equality, duplicate, set, order
Lists/ReorderingListsHow to reorder the elements in a list in Java, including reversing, shuffling, and sorting. 15list, ordering, sorting, shuffling, reversing, interface Comparator, interface Comparable, natural ordering
Lists/SlicingListsHow to obtain a well-defined part of a list in Java. 10list, slicing, sublist, tail, end, array, copying
Lists/TraversingListsThe different ways to iterate through the elements in a list in Java. 12list, iteration, enhanced for loop, for-each loop, stream, iterator, enumeration
Maps/BasicOperationsThe basic operations available on a Map, and how to use them. 6map, put, get, putIfAbsent
Maps/CopyingMapsThe many different ways to copies two map objects by copying all their entries. 7map, object copying
Maps/ImplementationsAn overview of the different implementations of interface Map offered by the JDK. 23Map, HashMap, LinkedHashMap, SortedMap, TreeMap, EnumMap, SequencedMap, IdentityHashMap, WeakHashMap, ConcurrentHashMap
Maps/InitializingMapsThe many different ways to initialize a map in Java, with technical explanations and their pros and cons. 30map, initialization, double-brace initialization, instance initializer block
Maps/MapAlgebraHow to easily implement different high-level operation involving maps using the bulk operation methods on collections. 3map, containAll, removeAll, retainAll
Maps/UpdatingMapsThe many different ways to update a map. 13map, update
Sets/ArrayToSetDifferent ways to convert an array to a set in Java. 6set, array
Sets/ImplementationsAn overview of the different implementations of interface Set offered by the JDK. 11set, sorted set
Sets/InitializingSetsThe many different ways to initialize a set in Java, with technical explanations and their pros and cons. 20sets, initialization, double-brace initialization, instance initializer block, varargs, Set factory method
Sets/UsingEnumSetWhat an EnumSet is and how to use one. 8set, enum, enumerated type
Sets/UsingLinkedHashSetThe features and behavior of the LinkedHashSet, a Set implementation that is also a sequence. 7set, sequence
Sets/UsingTreeSetThe features and behavior of the TreeSet, a Set implementation that is also a navigable sequence with a defined order. 13set, sequence, order
Introduction to Software Design
Chapter 1: Introduction/TwelveDaysSample program that outputs the text of the poem "The Twelve Days of Christmas" to the console. 10main method, Java library method, method parameter, recursion
Chapter 2: Encapsulation/CardClass representing a playing card and illustrating best practices for encapsulation in Java. The class creates immutable objects. 21abstraction, encapsulation, information hiding, design by contract, Primitive Obsession antipattern, private members, immutability, assert statements
Chapter 2: Encapsulation/DeckClass representing a deck of playing card and illustrating best practices for encapsulation of mutable objects in Java, including how to avoid reference leaks. 16mutable field, assert statement, escaping reference, unmodifiableList
Chapter 2: Encapsulation/RankAn enumerated type that represents the rank of a playing card. 7enumerated type, Primitive Obsession antipattern, uniqueness
Chapter 2: Encapsulation/SuitAn enumerated type that represents the suit of a playing card. 7enumerated types, Primitive Obsession antipattern, uniqueness
Chapter 3: Types and Interfaces/CardClass representing a playing card and illustrating effective use of interfaces and polymorphism. 7interface Comparable, interface Comparator, implicit declaration, Design by Contract, anonymous class
Chapter 3: Types and Interfaces/CardSourceExample of an interface with explanation of polymorphism. 5interface, polymorphism, implicitly public
Chapter 3: Types and Interfaces/ClientSample code that uses classes.list, static method
Chapter 3: Types and Interfaces/DeckClass representing a deck of playing card and illustrating iterable data structures and comparable behavior. 10interface Iterable, iteration, iterator, Design by Contract, interface Comparator, function object
Chapter 3: Types and Interfaces/RankAn enumerated type that represents the rank of a playing card. 1enumerated type
Chapter 3: Types and Interfaces/SuitAn enumerated type that represents the suit of a playing card. 1enumerated type
Chapter 4: Object State/CardClass representing a playing card and illustrating an application of the Flyweight pattern. 8Flyweight Pattern, enum map, greedy initialization, lazy initialization, static initialization block, private constructor
Chapter 4: Object State/CardSourceInterface with illustration of the Null Object pattern with a default method. 7interface, polymorphism, implicitly constant, anonymous class, Null Object pattern, default method
Chapter 4: Object State/ClientInterface with illustration of the Null Object pattern with a default method. 3Null Object pattern, inner classes
Chapter 4: Object State/DeckClass representing a deck of playing card and making use of the static factory methods, nested classes, and final fields. 15final field, nested class, inner class, static class, factory method
Chapter 4: Object State/GameModelApplication of the Singleton pattern. 3Singleton pattern, private constructor
Chapter 4: Object State/RankAn enumerated type that represents the rank of a playing card.enumerated type
Chapter 4: Object State/SuitAn enumerated type that represents the suit of a playing card.enumerated type
Chapter 5: Unit Testing/AbsTestSample JUnit5 test class for testing the method Math.abs() 7@Test annotation, unit test, naming convention, assertEquals, assert statement
Chapter 5: Unit Testing/CardClass representing a playing card and provided as a dependency for the test code.
Chapter 5: Unit Testing/FoundationPileSample class under test.
Chapter 5: Unit Testing/GameModelSample class under test.
Chapter 5: Unit Testing/GameModelViewDependency of the sample class under test GameModel. Provided here just to make the code compile.
Chapter 5: Unit Testing/MetaprogrammingSamplesCommon usage patterns for the Java reflection API, an application of the concept of metaprogramming. 6class Class, type wildcard, unknown type, metaprogramming, Java reflection, class literal, bounded wildcard
Chapter 5: Unit Testing/MoveDependencies of the sample class under test GameModel. Provided here just to make the code compile.
Chapter 5: Unit Testing/PlayingStrategyDependencies of the sample class under test GameModel. Provided here just to make the code compile.
Chapter 5: Unit Testing/RankAn enumerated type that represents the rank of a playing card.enumerated type
Chapter 5: Unit Testing/SuitAn enumerated type that represents the suit of a playing card.enumerated type
Chapter 5: Unit Testing/TestFoundationPileSample test class for the production class FoundationPile, illustrating the use of scaffolding and various testing patterns. 10scaffolding, test instance lifecycle, JUnit5, @Test annotation, helper method, test fixture, encapsulation, assertThrows, try/fail pattern
Chapter 5: Unit Testing/TestGameModelSample test class for the production class GameModel, illustrating testing with stubs. 3JUnit5, @Test annotation, test stub
Chapter 6: Composition/CardClass representing a playing card and provided as a dependency for the rest of the code in this chapter.
Chapter 6: Composition/CardSourceExample of an interface that includes polymorphic copying. 1interface, polymorphic copying
Chapter 6: Composition/CardStackWrapper around a list, provided as a dependency to the other code in this chapter.
Chapter 6: Composition/CommandInterface that is the main solution element of the Command design pattern. 3Command pattern, class Optional
Chapter 6: Composition/CompositeCardSourceA CardSource implementation that represents an aggregation of zero or more card sources. Application of the Composite design pattern. 5Composite pattern, vararg, assert statement, polymorphic copying
Chapter 6: Composition/DeckClass representing a deck of playing card and illustrating the concept of an instance command factory method. 4polymorphic copying, anonymous class, factory method, optional type
Chapter 6: Composition/GameModelStub of a class that represents the state of a card game. Illustrates the use of the Prototype design pattern. 2Prototype pattern, polymorphic copying, @SuppressWarning
Chapter 6: Composition/LoggingDeckIllustrates composition within a type hierarchy.interface implementation, object aggregation, delegation
Chapter 6: Composition/LoggingDecoratorApplication of the Decorator design pattern. 4Decorator pattern, delegation
Chapter 6: Composition/MemorizingDecoratorApplication of the Decorator design pattern. 1Decorator pattern, delegation
Chapter 6: Composition/RankAn enumerated type that represents the rank of a playing card.enumerated type
Chapter 6: Composition/SuitAn enumerated type that represents the suit of a playing card.enumerated type
Chapter 7: Inheritance/AbstractDecoratorAn abstract class for classes that serve as decorators in the Decorator design pattern. 5abstract class, Decorator pattern, protected visibility, protected constructor
Chapter 7: Inheritance/AbstractMoveAn abstract class that illustrates an application of the Template Method design pattern. 10abstract class, abstract method, protected visibility, Template Method pattern
Chapter 7: Inheritance/CardClass representing a playing card and provided as a dependency for the rest of the code in this chapter.
Chapter 7: Inheritance/CardMoveSample concrete class that extends an abstract class and plays a role in the Template Method design pattern. 2final class, Template Method pattern
Chapter 7: Inheritance/CardSourceInterface provided as a dependency for the rest of the code in this chapter.
Chapter 7: Inheritance/CardStackWrapper around a list, provided as a dependency to the other code in this chapter.
Chapter 7: Inheritance/DeckClass representing a deck of playing card and provided as a dependency for the other classes in this topic.
Chapter 7: Inheritance/GameModelStub class to represent a client of the Move class hierarchy.
Chapter 7: Inheritance/LoggingDecoratorExample of a decorator that prints call events to the console. 1super calls, Decorator pattern, inheritance
Chapter 7: Inheritance/MemorizingDeckExample of inheritance with method overriding and super calls. 5inheritance, overriding, super call, field initialization, polymorphic copying
Chapter 7: Inheritance/MoveInterface provided as dependency for other code in the chapter.
Chapter 7: Inheritance/RankAn enumerated type that represents the rank of a playing card.enumerated type
Chapter 7: Inheritance/SuitAn enumerated type that represents the suit of a playing card.enumerated type
Chapter 8: Inversion of Control/AbstractCardSourceVisitorAn abstract class for classes that implements the Visitor interface. 1abstract class, Visitor pattern
Chapter 8: Inversion of Control/AceDetectorA sample concrete observer in the Observer design pattern. 1Observer pattern, concrete observer, callback
Chapter 8: Inversion of Control/CardClass representing a playing card and provided as a dependency for the rest of the code in this chapter.
Chapter 8: Inversion of Control/CardSequenceWrapper around a list of cards and provided as a dependency for the rest of the code in this chapter.
Chapter 8: Inversion of Control/CardSourceAn interface enhanced to support integration with the Visitor design pattern. 1Visitor pattern, accept method
Chapter 8: Inversion of Control/CardSourceVisitorAn interface defining an abstract visitor in the Visitor design pattern. 1Visitor pattern, accept method
Chapter 8: Inversion of Control/CardStackWrapper around a list of cards and provided as a dependency for the rest of the code in this chapter.
Chapter 8: Inversion of Control/CardStackObserverAn interface defining the abstract observer in the Observer design pattern. 2Observer pattern, callback method, adapter class, push data-flow
Chapter 8: Inversion of Control/ChecksContainmentVisitorConcrete visitor implementation that accumulates state during traversal. 11Visitor pattern, object state, accept method, visit method, data flow
Chapter 8: Inversion of Control/CompositeCardSourceComposite object that defines a structure that can be traversed by a visitor in the Visitor design pattern.
Chapter 8: Inversion of Control/CounterExample of a concrete observer in the Observer design pattern.Observer pattern, concrete observer
Chapter 8: Inversion of Control/CountingVisitorExample of a concrete stateful visitor in the Visitor design pattern.Visitor pattern
Chapter 8: Inversion of Control/DeckClass representing a deck of playing card and provided as a dependency for the other classes in this topic.
Chapter 8: Inversion of Control/DriverExample code for creating and using different kinds of visitors in the Visitor design pattern. 5Visitor pattern
Chapter 8: Inversion of Control/GenericVisitorSampleSample application of the Visitor design pattern using generic types instead of state accumulation.Visitor pattern, generic type
Chapter 8: Inversion of Control/LuckyNumberSmall GUI application illustrating the Observer pattern as well as GUI programming with JavaFX. 26Observer pattern, JavaFX, application class, grid, GUI components, event, event handler, observer registration, observer notification
Chapter 8: Inversion of Control/ObservableCardStackA stack of card objects whose state changes can be observed in accordance with the Observer design pattern. 4Observer pattern, inheritance
Chapter 8: Inversion of Control/PrintVisitorA simple example of a concrete visitor in the Visitor design pattern.Visitor pattern
Chapter 8: Inversion of Control/RankAn enumerated type that represents the rank of a playing card.enumerated type
Chapter 8: Inversion of Control/StructurePrinterVisitorA 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/SuitAn enumerated type that represents the suit of a playing card.enumerated type
Chapter 9: Functional Design/AutoPlayerStrategy design pattern applied using functional-style design. 2Strategy pattern, functional programming
Chapter 9: Functional Design/CardImplementation of a playing card with factory functions to create Comparators using functional-style programming. 12interface Comparable, functional programming, factory method, lambda expression
Chapter 9: Functional Design/CardSelectionStrategyExample of a user-defined functional interface. 1functional interface
Chapter 9: Functional Design/CardSourceAn interface used in other code samples in this chapter.
Chapter 9: Functional Design/CardStackWrapper around a list of cards and provided as a dependency for the rest of the code in this chapter.
Chapter 9: Functional Design/CardUtilsCode to demonstrate how to use references to static methods.
Chapter 9: Functional Design/ConsumingDecoratorAn example of using the Consumer interfaceinterface Consuming, Decorator pattern
Chapter 9: Functional Design/DeckA class representing a deck of cards with a method to stream all the cards in the deck. 1interface Stream
Chapter 9: Functional Design/FilterExamples of a user-defined functional interface.
Chapter 9: Functional Design/InfiniteCardSourceDemonstrates how to use the Supplier interface to obtain card in the context of a card source that can supply an infinity of cards. 2interface Supplier
Chapter 9: Functional Design/ObservableDeckSample observable object where the Observer design pattern is applied using functional-style design. 2Observer pattern, functional programming, interface Consumer, functional interface
Chapter 9: Functional Design/RankAn enumerated type that represents the rank of a playing card.enumerated type
Chapter 9: Functional Design/SamplesNumerous small samples of functional programming in action.functional programming, lambda expression, method reference, functional interface, stream
Chapter 9: Functional Design/SuitAn enumerated type that represents the suit of a playing card.enumerated type
Solutions 1: Introduction/Exercise01Sample program that outputs the text of the poem "The Twelve Days of Christmas" to the console and demonstrates recursion vs. iteration. 2twelve days of Christmas, iteration, recursion
Solutions 1: Introduction/Exercise02Sample program that outputs the text of the poem "The Twelve Days of Christmas" to the console and demonstrates how to parameterize a program. 7twelve days of Christmas, command-line argument,
Solutions 1: Introduction/Exercise03Sample 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. 5twelve days of Christmas, command-line argument,
Solutions 1: Introduction/Exercise04Sample 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. 8twelve days of Christmas, command-line argument, resource bundle, localization
Solutions 2: Encapsulation/Exercise01Representing an int value using Booleans and why this is not a good idea. 5types, Boolean
Solutions 2: Encapsulation/Exercise02Representing a playing card as an enumerated type. 1enumerated type
Solutions 2: Encapsulation/Exercise03Adding a method with randomness to a class. 3class design
Solutions 2: Encapsulation/Exercise04Adding a method to an enum in Java. 2enumerated type
Solutions 2: Encapsulation/Exercise05Code using proper abstractions to work with playing card data. 2primitive obsession, refactorings
Solutions 2: Encapsulation/Exercise06Code to implement a sequence based on values of enumerated types. 1circular sequence, enum method
Solutions 2: Encapsulation/Exercise07Code to implement a playing card that can be a joker. 6nullability
Solutions 2: Encapsulation/Exercise08Code to implement a playing card that can be a joker of different kinds. 9enumerated types
Solutions 2: Encapsulation/Exercise09Sample demonstrating how to implement a copy constructorcopy constructor
Solutions 2: Encapsulation/Exercise10Sample demonstrating how to implement a copy constructor on an aggregate object. 3object aggregation, copy constructor
Solutions 2: Encapsulation/Exercise11Empty sample.object diagram
Solutions 2: Encapsulation/Exercise12Sample demonstrating how to use enumerated types 5enumerated type
Solutions 3: Types and Interfaces/Exercise01To03A well-encapsulated class representing a hand (collection) of cards. 11interface implementation, anonymous class, iterator
Solutions 3: Types and Interfaces/Exercise04Diagram only.class diagram
Solutions 3: Types and Interfaces/Exercise06Example of a stateful comparator (not recommended). 1Comparator
Solutions 3: Types and Interfaces/Exercise08Diagram only.class diagram
Solutions 3: Types and Interfaces/Exercise09Example of dependency injection. 3dependency injection, comparable, iterable
Solutions 3: Types and Interfaces/Exercise10Diagram only.class diagram
Solutions 3: Types and Interfaces/Exercise11Diagram only.class diagram
Solutions 4: Object State/Exercise01Diagram only.state diagram
Solutions 4: Object State/Exercise02Diagram only.state diagram
Solutions 4: Object State/Exercise03How to use optionals in Java. 5encapsulation, optional types
Solutions 4: Object State/Exercise04How to use the null design pattern in Java. 3null object design pattern
Solutions 4: Object State/Exercise05How to use the null design pattern in Java. 1null object design pattern, interface
Solutions 4: Object State/Exercise06How to implement the equals method in Java. 6equals method
Solutions 4: Object State/Exercise07How to apply the flyweight pattern with pre-initialization of the values. 5Flyweight design pattern, map interface
Solutions 4: Object State/Exercise08How to apply the flyweight pattern with lazy initialization of the values. 3Flyweight design pattern, map interface
Solutions 4: Object State/Exercise09How to apply the Singleton design. 3Singleton design pattern
Solutions 5: Unit Testing/Exercise01Sample unit tests for the method Math.min. 3unit testing
Solutions 5: Unit Testing/Exercise02Sample unit tests for the method Math.cos. 7unit testing, floating-point arithmetics, trigonometry
Solutions 5: Unit Testing/Exercise03Sample unit tests for the method String#concat. 1unit testing, equality, string
Solutions 5: Unit Testing/Exercise04Object diagram of an object graph that involves Java reflection.metaprogramming, object diagram
Solutions 5: Unit Testing/Exercise05Program 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 5metaprogramming, reflection, numbers
Solutions 5: Unit Testing/Exercise06Program to verify whether it is possible to call any parameterless method of class String on an empty string without raising an exception. 2metaprogramming, reflection, string
Solutions 5: Unit Testing/Exercise07Program to verify whether it is possible to call any parameterless method of class String on an empty string without raising an exception. 4unit testing, stack, test fixture
Solutions 5: Unit Testing/Exercise08to10Unit tests for private members 1unit testing, private members
Solutions 5: Unit Testing/Exercise11Unit tests demonstrating the use of stubs. 2unit testing, stubs