What you will learn in 100 Java Mistakes and How to Avoid Them
Chapter by chapter
Concepts explained in this book
- static analysisA static analysis tool is software that examines code without executing it to detect defects, policy violations, or other properties.
- equality by valueThe equals method is the Object method conventionally overridden to determine logical equality between objects.
- numerical overflowFloating-point overflow is a computation exceeding the finite representable range of a floating-point type, typically producing infinity.
- compareTo methodThe compareTo method is the Comparable interface method that compares the receiver with another object and returns a negative, zero, or positive integer.
- streamingThe Java Stream API provides pipelines for processing sequences of elements through intermediate and terminal operations.
- boxed primitiveA boxed primitive type is a reference type that wraps a Java primitive value, such as Integer wrapping int, and can represent null.
- operator precedenceOperator precedence is the set of Java rules that determines how operators in an expression are grouped and evaluated relative to one another.
- loopA for loop is a Java loop statement with initialization, condition, and iteration components that controls repeated execution.
- immutable collectionAn immutable collection is a collection whose state cannot be changed after construction.
- terminal operationA terminal operation is a stream operation that triggers evaluation of a Java stream pipeline and produces a final result or side effect.
- conditional logicA branching statement is a Java control-flow statement that selects among alternative execution paths.
- testA test case is a defined set of inputs, execution conditions, and expected results for evaluating software behavior.
- initializerA constructor is a special Java member that initializes a newly created object and may throw exceptions or produce side effects.
- raw typeA raw type is a generic Java type used without its type arguments, disabling compile-time checking for those arguments.
- bit operationThe bitwise XOR operator computes a bit-by-bit exclusive disjunction of integer operands.
- side effectA side effect is an observable state change or external interaction caused by evaluating an operation in addition to producing its direct result.
- ClassCastExceptionClassCastException is the Java runtime exception thrown when a value cannot be cast to the requested reference type, including when identically named classes come from different class loaders.
- collectionA collection is an object representing a group of elements managed through Java's collection abstractions.
- unboxingAn unboxing conversion converts a Java wrapper object to the corresponding primitive value, and can throw NullPointerException when the object is null.
- data conversionType conversion is the transformation or interpretation of a value from one Java type to another.
- iteratorAn iterator is an object that traverses the elements of a collection and can optionally remove elements through its iteration protocol.
- boxingA boxing conversion converts a Java primitive value to an object of its corresponding wrapper type, either explicitly or implicitly.
- implicit conversionImplicit conversion is an automatic type conversion performed by Java according to its conversion rules without an explicit cast or conversion call.
- indexOf methodThe Java String.indexOf method returns the index of the first occurrence of a specified character or substring, or -1 when no occurrence exists.
- enumAn enum type is a Java class-like type that defines a fixed set of named constants.
- constant expressionA compile-time constant is a final value whose initializer can be evaluated by the compiler and embedded where it is referenced.
- parenthesisA parenthesis in a Java expression explicitly groups subexpressions and overrides ordinary operator precedence.
- bit shiftingA bitwise shift operator moves the binary representation of an integer left or right by a specified number of bit positions.
- Comparable interfaceComparable is a Java interface whose implementation defines a natural ordering for instances through compareTo.
- ArrayDequeArrayDeque is a Java resizable-array implementation of the Deque interface that supports insertion and removal at both ends.
- StringBuilderStringBuilder is a mutable Java character sequence class that supports efficient string construction and modification.
- comparator contractA comparator contract is the set of consistency and ordering requirements that a comparison method must satisfy.
- Collections.unmodifiableXYZCollections.unmodifiableXYZ denotes the Java Collections factory methods that expose read-only views of collections.
- setA set is a collection abstraction that stores distinct elements without duplicate membership.
- NullPointerExceptionNullPointerException is the Java runtime exception raised when an operation dereferences or otherwise improperly uses a null reference.
- equality contractAn equality contract is the set of behavioral requirements governing an equals implementation, including properties such as reflexivity, symmetry, transitivity, consistency, and null handling.
- Math.addExactMath.addExact is a Java static method that returns an exact integer sum and throws ArithmeticException when the sum overflows.
- Math.hypotMath.hypot is a Java static method that returns the Euclidean hypotenuse of two arguments with numerical handling designed to reduce overflow and underflow.
- underflowUnderflow is a numerical condition in which a computed result falls below the representable range of its numeric type, potentially losing precision or becoming zero.
- unsigned right shiftAn unsigned right shift moves integer bits toward less significant positions while filling the most significant positions with zeros.
- Long literalA Long literal is a numeric literal whose syntax specifies that its value has the Kotlin Long integer type.
- stack overflowA stack overflow is exhaustion of the call stack caused by excessive or unbounded nested execution.
- defensive checkA defensive check is an input validation performed at a boundary to reject invalid values before they can corrupt program state.
- infinite loopAn infinite loop is a loop whose execution continues indefinitely because its termination condition is never reached or satisfied.
- intermediate operationAn intermediate operation is a Java Stream pipeline operation that describes a transformation or selection and produces another stream for further processing.
- Map.computeIfAbsentMap.computeIfAbsent is a Java Map operation that computes and associates a value for a key when no non-null value is already associated with that key.
- instanceof operatorThe instanceof operator tests whether an object or reference is compatible with a specified runtime type or constructor according to the programming language’s rules.
- function overloadingA method overload is one of multiple methods with the same name but different parameter lists in a class or interface.
- concurrent modificationConcurrent modification is a structural change to a collection or map while an operation on that same structure is in progress.
- atomicityAn atomic request is an operation that observes or updates its target as one indivisible action without an intervening state change.
- hashCode methodThe hashCode method is a Java object method that returns an integer hash value consistent with the object's equality contract.
- CheckReturnValue annotationThe CheckReturnValue annotation marks methods or program elements whose returned values should be checked by analysis tools.
- read methodThe InputStream read method reads bytes into a buffer or returns a byte or end-of-stream indicator depending on its overload.
- readNBytes methodThe readNBytes method reads up to or the requested number of bytes from an input stream, with an overload that returns a new byte array.
- circular dependencyA circular dependency is a dependency cycle in which class initialization directly or indirectly requires initialization of a class that depends back on the original class.
- type erasureType erasure is Java's compilation process of removing generic type information from runtime representations while preserving compile-time generic checks.
- unchecked castAn unchecked cast is a cast whose compatibility cannot be fully verified by the compiler or at runtime because of erased generic type information.
- code coverageCode coverage is the fraction of program code elements executed during a test suite.
- finalThe final modifier is a Java declaration modifier that prevents reassignment of a local variable after its initialization or assignment.
- pattern matching in instanceofPattern matching in instanceof is a Java language feature that combines an instanceof type test with conditional pattern variable binding.
- assertionAn assert statement is a Java language statement that evaluates a boolean condition and raises an assertion failure when the condition is false and assertions are enabled.
- String.toLowerCaseString.toLowerCase is a Java String method that returns a string with its characters converted to lowercase according to an optionally specified locale.
- BooleanBoolean is the Java wrapper class for the primitive boolean type, with TRUE and FALSE instances and the possibility of a null reference.
- copyOf methodA Java collection copyOf method creates an unmodifiable collection copy that rejects null elements and may return an existing suitable immutable copy.
- Objects.requireNonNullObjects.requireNonNull is a Java utility method that returns a non-null reference or throws NullPointerException when its argument is null.
- method referenceA method reference is a Java expression that refers to an existing method or constructor as an implementation of a functional interface.
- arrayAn array is an indexed Java object or primitive container with a fixed length and a single component type.
- lambdaA lambda expression is an anonymous Java function-like expression that provides an implementation compatible with a functional interface.
- class initializationClass initialization is the JVM process that initializes a class's static fields and static initialization blocks before the class is first actively used.
- missing valueThe null value is Java's special reference value denoting the absence of an object reference.
- property-based testingProperty-based testing verifies general behavioral properties by running tests against many generated inputs, often including randomized inputs.
- variadic argumentsA variadic function or parameter accepts a variable number of arguments, often collecting the supplied values into a sequence of a specified type.
- wildcard typeA wildcard type is a Java generic type argument represented by a question mark that permits constrained or unconstrained type variation.
- parallel streamA parallel stream is a Stream configured to process elements using multiple execution threads when the implementation permits.
- list methodremove is a queue operation that retrieves and removes an element, throwing an exception when no element is available.
- comparison methodA comparison method is a method such as Comparator.compare or Comparable.compareTo that determines the ordering relationship between two values.
- instance variableAn instance variable is data associated with a particular object, rather than shared across all instances of its class or type.
- static fieldA static field is a Java class variable whose storage is associated with the class rather than with each object instance.
- concatenationConcatenation is the operation of joining ordered sequences end to end to form a single sequence.
- nanNaN is a special floating-point value representing an undefined or unrepresentable numeric result and that is unequal to every value, including itself.
- hash valueA hash code is an integer value returned by an object's hashCode method for use by hash-based data structures.
- pattern matching for switchPattern matching for switch is a Java language feature that lets switch cases match values by type or structural pattern and bind pattern variables.
- listList is the Java collection interface for an ordered sequence of elements that may contain duplicates.
- containsCollection.contains is the Java Collection interface method that tests whether a collection contains an object equal to a specified value.
- float64Float64 is a 64-bit floating-point numeric type, commonly represented using the IEEE 754 binary64 format.
- recursionRecursion is a programming technique in which a method or algorithm invokes itself to solve a problem through smaller subproblems.
- augmented assignmentAugmented assignment is syntax that combines an operation with assignment to update a variable or object using its current value.
- Comparator.compareThe compare method is the Comparator method that returns a negative, zero, or positive integer according to the ordering of two arguments.
- List.copyOfList.copyOf is a Java factory method that creates an unmodifiable list containing the elements of a supplied collection.
- surrogate pairA surrogate pair is two UTF-16 code units that together encode one Unicode code point outside the Basic Multilingual Plane.
- Class.isInstanceClass.isInstance is a reflection API method that tests whether an object is an instance of the represented runtime class or one of its subclasses.
- quick fixA quick fix is an automated or semi-automated code transformation offered in response to a diagnostic.
- case statementA switch statement is a Java control-flow statement that selects and executes a branch based on the value of an expression.
- Integer.compareInteger.compare is a Java library method that compares two int values without computing their potentially overflowing difference.
- get/put sequenceA get/put sequence is a map-update pattern that separately retrieves a value and then inserts or updates a mapping.
- static typingA static type system determines and checks the types of program expressions before execution.
- Unchecked/Unconfirmed Cast warningAn unchecked cast warning is a compiler diagnostic indicating that a cast involving generic types cannot be verified for type safety.
- default system localeThe default locale is the locale selected by the JVM from operating-system preferences, environment variables, or JVM system properties when no locale is specified explicitly.
- iterator contractThe iterator contract is the behavioral specification governing how an Iterator reports availability, returns elements, and signals exhaustion.
- logical AND operatorThe logical && operator evaluates boolean operands and produces true only when both operands are true.
- List.ofList.of is a Java library factory method that creates an unmodifiable list containing the supplied elements.
- attributeAn annotation is structured metadata attached to program elements that tools or language processors can inspect.
- cycleA cycle is a path in a graph or linked data structure that eventually returns to an element already visited.
- infinite recursionInfinite recursion is recursion that continues without reaching a terminating condition and eventually exhausts available execution resources.
- Map.mergeMap.merge is a Java Map interface method that inserts a non-null value for an absent key or combines it with an existing value using a remapping function.
- getClassgetClass is the Object method that returns the runtime class of the object on which it is invoked.
- type patternA type pattern is a Java pattern that tests whether a value has a specified type and binds it to a variable of that type.
- comparator invariantA comparator invariant is a property of comparison results, such as transitivity, that must remain consistent across compared values.
- escape sequenceAn escape sequence is a backslash-initiated notation in a string or character literal that represents a special character or character value.
- TimSortTimSort is a stable hybrid sorting algorithm derived from merge sort and insertion sort that exploits existing ordered runs.
- Arrays.setAllArrays.setAll is a Java API operation that fills an array by computing each element from its index with a supplied function.
- off-by-one errorAn off-by-one error is a boundary error in which an iteration or indexing operation starts or stops one position or value too early or too late.
- narrowing conversionA narrowing conversion converts a value to a type with a smaller representable range or less general numeric domain, potentially discarding information.
- code reviewCode review is the systematic examination of source code by one or more developers to identify defects and improve quality.
- SoftReferenceSoftReference is a Java reference type whose referent may be reclaimed in response to memory demand.
- weak referenceWeakReference is a Java reference type whose referent may be reclaimed when it is not strongly reachable.
- floating-point arithmeticA floating-point number is a numerical value represented with a significand and an exponent, allowing fractional values and a wide range of magnitudes with finite precision.
- basic multilingual planeThe Basic Multilingual Plane is Unicode's plane of code points from U+0000 through U+FFFF.
- BreakIteratorBreakIterator is a Java text-processing API that determines locale-sensitive boundaries between units such as characters, words, lines, or sentences.
- character boundaryA character boundary is a position in text at which a user-perceived character sequence can be safely divided.
- code pointA Unicode code point is a numeric value identifying an abstract character or character-related symbol in the Unicode character set.
- codepoint-centered apiA codepoint-centered API is an interface that represents and processes text using Unicode code points rather than individual UTF-16 code units.
- codePointAtcodePointAt is a Java String API method that returns the Unicode code point beginning at a specified UTF-16 char index.
- combining characterA combining character is a Unicode character that modifies the appearance or interpretation of a preceding base character.
- combining character sequenceA combining character sequence is a base character together with one or more attached combining characters.
- test-driven developmentTest-driven development is a software development methodology in which tests are written before the implementation code.
- reference equalityReference equality is Java's identity comparison of two references to determine whether they denote the same object.
- code analysisCode analysis is the systematic examination of source code, compiled code, or program behavior to determine its structure, properties, behavior, or defects.
- branch coverageBranch coverage is the fraction of control-flow branches exercised by a test suite.
- idempotencyAn idempotent operation is an operation whose repeated application has the same resulting effect as applying it once, even though it may produce a side effect.
- idempotent loop bodyAn idempotent loop body is a loop body whose repeated execution does not further change the relevant program state after an initial execution.
- removeIf methodThe removeIf method removes elements from a collection that satisfy a supplied predicate.
- deletionA collection removal method is an operation that removes matching elements or mappings from a collection or map.
- tail recursionTail recursion is recursion in which the recursive call is the final operation performed by the method.
- operatorA Java operator is a language symbol or keyword that performs an operation on one or more operands.
- peekA peek operation is a Stream intermediate operation that applies a supplied Consumer to elements as they pass through the pipeline without changing their values.
- current timeCurrent time is the temporal value representing the present moment as obtained from a clock, optionally including its date and time zone.
- file systemA filesystem is a system that organizes and provides access to files and directories on storage or through a mounted hierarchy.
- Files.readAttributesFiles.readAttributes is a Java NIO method that reads a filesystem entry's attributes in a single operation and returns them as an attribute view or map.
- flaky testA flaky test is an automated test whose result varies between runs despite unchanged code and inputs.
- atomic queryAn atomic query is a retrieval operation whose observed results are obtained as one indivisible filesystem action.
- thread safetyThread safety is the property that concurrent execution by multiple threads preserves an object's or component's correctness and consistency.
- null handlingA null check is a condition that tests whether a reference has the null value.
- class initialization monitorA class initialization monitor is the JVM synchronization mechanism on which threads wait while a class initializer is running.
- replace methodThe Java String.replace method returns a string in which matching occurrences of a target character or sequence are replaced with a specified replacement character or sequence.
- Comparator.comparingComparator.comparing is a Java factory method that creates a comparator by extracting a comparison key from each object.
- arrange act assert patternThe Arrange, Act, Assert pattern structures a test into setup, execution of the behavior under test, and verification of expected results.
- widening conversionA widening conversion converts a value to a type with a broader representable range or compatible numeric domain without requiring an explicit cast or conversion operation.
- Objects.equalsObjects.equals is a Java utility method that compares two references for equality while treating two null references as equal.
- condition dominanceCondition dominance is a control-flow relationship in which one condition can be true only when another condition is also true, making the dominated branch unreachable when tested afterward.
- mutually exclusive conditionMutually exclusive conditions are conditions that cannot be true simultaneously for the same program state.
- Objects.hashObjects.hash is a Java library method that computes a hash code from a sequence of object values.
- stringA string is a programming-language value representing an ordered sequence of characters or character units as text.
- format stringA format string is a string containing directives that specify how values or text should be interpreted or formatted.
- MapHashMap is a Java map implementation that stores key-value associations using hashing.
- accumulatorAn accumulator function combines two values during a reduction operation to produce another value.
- associativityAssociativity is the property that the grouping of operands does not change the result of an operation.
- forEachOrderedforEachOrdered is a Java Stream terminal operation that applies an action to elements while preserving the stream's encounter order.
- identity elementAn identity element is a value that leaves another operand unchanged when combined with it by an operation.
- stateful mapping operationA stateful mapping operation produces an element using information retained from previously processed elements.
- pure functionA stateless function computes each result without depending on mutable state or other invocations of the function.
- pairmappairMap is a utility operation that maps each pair of adjacent stream elements to a resulting element.
- FastUtilFastUtil is a Java library providing high-performance collections specialized for primitive and other commonly used types.
- byte typeThe byte type is Java's signed 8-bit integer primitive type, representing values from -128 through 127.
- Map.computeMap.compute is a Java Map interface method that recomputes a key's value and removes the mapping when the remapping result is null.
- Map.putIfAbsentMap.putIfAbsent is a Java Map interface method that associates a value when a key has no non-null mapped value and returns the prior value.
- Math.floorModMath.floorMod is a Java method that computes a floor-modulus result with a nonnegative remainder for a positive modulus.
- boundary checkA bounds check is a validation that an index or indexed range lies within the permitted limits of a data structure.
- IndexOutOfBoundsExceptionIndexOutOfBoundsException is a Java runtime exception thrown when an index is outside the valid range of a sequence or indexed data structure.
- NonNegative annotationThe NonNegative annotation declares that an annotated numeric value or parameter must not be less than zero.
- Objects.checkFromIndexSizeObjects.checkFromIndexSize is a Java utility method that validates an index and range size against a sequence length.
- Range annotationThe Range annotation declares explicit lower and upper bounds for an annotated numeric value or parameter.
- format methodString.format is a Java API method that returns a formatted string constructed from a format string and supplied arguments.
- Add methodCollection.add is a Java Collection operation that inserts a single element into a collection.
- Collection.addAllCollection.addAll is a Java Collection operation that inserts all elements from another collection.
- Collection.streamCollection.stream is a Java Collection operation that creates a sequential Stream over the collection's elements.
- exhaustive switch statementAn exhaustive switch statement is a Java switch statement whose cases cover every permitted value or subtype in its selector domain.
- sealed typeA sealed interface is a Java interface that restricts which classes or interfaces may directly implement or extend it.
- Stream.ofStream.of is a Java factory method that creates a Stream from supplied elements.
- InferInfer is a static analyzer that performs deep analysis of code to detect certain potential defects.
- NonNullByDefault annotationA NonNullByDefault annotation declares that applicable types, parameters, or return values are non-null unless explicitly specified otherwise.
- nullable annotationA nullity annotation is metadata declaring whether a program value, parameter, field, or method result may be null.
- SonarLintSonarLint is a code-quality tool that provides static analysis feedback in development environments and build workflows.
- recursive traversalRecursive traversal is the process of visiting a hierarchical or graph-like structure by recursively processing related child elements.
- treeA tree-like data structure organizes elements into parent-child relationships and ordinarily has no cycles.
- enhanced for statementAn enhanced for statement is Java syntax that traverses an Iterable or array by repeatedly obtaining elements for a loop body.
- iterableIterable is a Java interface whose objects can provide an Iterator for traversing their elements.
- Iterator.hasNextIterator.hasNext is the Java Iterator method that reports whether another element is available without advancing the iteration.
- nextIterator.next is the Java Iterator method that returns the next element and throws NoSuchElementException when none remains.
- NoSuchElementExceptionNoSuchElementException is the Java runtime exception indicating that an iterator or enumeration has no next element available.
- EqualsVerifierEqualsVerifier is a Java library that tests whether equals and hashCode implementations comply with their contracts.
- genericsA generic type is a Java type declaration or use parameterized by one or more type arguments.
- BigDecimalBigDecimal is the Java arbitrary-precision decimal numeric class in java.math.
- non-short-circuit operatorA non-short-circuit operator is a Java boolean operator that evaluates both operands regardless of whether the left operand already determines the result.
- short-circuit evaluationA short-circuit operator is a Java boolean operator that skips evaluation of its right operand when the result is already determined by the left operand.
- boolean operationA Boolean operation combines or transforms truth-valued inputs according to logical rules to produce a truth-valued result.
- variable arity callA variable arity call is a method invocation that supplies an arbitrary number of arguments to a variable arity parameter.
- filteringFiltering is the operation of selecting or excluding items from data or a collection according to specified criteria.
- comparator combinatorA comparator combinator is a method that constructs or composes a comparator from comparison criteria and ordering rules.
- sequence of keysA sequence of keys is an ordered set of object values compared lexicographically to determine object ordering.
- hash collisionA hash collision occurs when distinct inputs to a hash function produce the same hash value or map to the same hash-table location.
- identityReference identity is the property of two references denoting the same object instance, regardless of object content.
- IdentityHashMapIdentityHashMap is a Java map implementation that compares keys by reference identity rather than by equals and hashCode.
- escape characterA backslash is an escape character used by Java string literals and by regular-expression syntax to alter the interpretation of the following character.
- splitSplit is an operation or function that divides a string or sequence into parts according to a separator, pattern, or other rule.
- Arrays.equalsArrays.equals is a Java utility method that tests whether two arrays have equal lengths and pairwise equal elements.
- atomic typeAn atomic variable is a Java concurrency object that supports indivisible access and updates to a stored value.
- specialized primitive collectionA specialized primitive collection is a collection implementation that stores primitive values directly and provides operations accepting those values without boxing.
- Java recordA Java record is a restricted class declaration for modeling data-carrier objects with a compact syntax for components and associated members.
- class loaderA class loader is a JVM component that locates, loads, and defines classes, with the defining loader contributing to a class's runtime identity.
- heapThe heap is the runtime memory area from which dynamically allocated objects and data structures are allocated.
- localeA locale is a set of regional and linguistic conventions that affects operations such as case conversion and number formatting.
- static-analysis warningA static analyzer warning is a diagnostic reported by static analysis that is irrelevant, excessive, or otherwise not useful to the developer.
- assertNotEqualsassertNotEquals is a test assertion that succeeds when two supplied values are considered unequal according to the testing framework's equality semantics.
- replaceAll methodThe Java String.replaceAll method returns a string in which substrings matching a regular expression are replaced with a replacement string.
- uriA URI is a Uniform Resource Identifier that identifies a resource using a standardized syntax and provides component-based equality semantics.
- De Morgan's lawsDe Morgan's laws state that negating a disjunction is equivalent to conjoining the negated operands, and negating a conjunction is equivalent to disjoining them.
- logical ORThe logical || operator evaluates boolean operands and produces true when at least one operand is true.
- ConcurrentModificationExceptionConcurrentModificationException is the Java runtime exception that signals an unsupported structural modification detected during iteration or another collection operation.
- CopyOnWriteArrayListCopyOnWriteArrayList is a thread-safe Java list implementation that copies its backing array whenever the list is modified and provides iterators over a snapshot.
- fail-fast behaviorFail-fast behavior is a design in which an operation reports a detected invalid state as soon as possible instead of continuing with potentially unreliable results.
- string literalA string literal is a Java source-code literal representing a sequence of characters using double quotation marks.
- optionOptional is a Java standard-library container type representing either a present non-null value or an empty state.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
