Double NaN Never Equals Itself
NaN compares false against everything including itself: use Double.isNaN for detection and Double.compare for ordering, which treats NaN as equal to itself.
Page 2 of 7
NaN compares false against everything including itself: use Double.isNaN for detection and Double.compare for ordering, which treats NaN as equal to itself.
doubleToLongBits exposes the IEEE 754 layout: plus and minus zero differ only in the sign bit, every NaN canonicalizes, and the raw form keeps payloads.
Count terminal columns where CJK and fullwidth characters occupy two cells, so padded tables align where String length() undercounts wide text.
Sign a payload with the Ed25519 JCA Signature API and verify both the original bytes and a tampered copy, which must fail.
Validate user emails with a conservative regex pattern that accepts common shapes and rejects spaces or missing domains.
exceptionallyCompose swaps a failed future for a fallback future instead of a plain value, so recovery can itself be an async call.
Stop a pool politely: shutdown stops intake, awaitTermination grants a grace period, shutdownNow interrupts stragglers, then one more wait confirms.
An uncaught execute() task kills only the worker and the pool spawns a replacement, while submit() traps the exception inside its Future.
Create a symlink and read back the raw target stored inside it with Files.readSymbolicLink, keeping toRealPath as the follow-the-link view of the same path.
Stream the whole directory tree with Files.walk, sort by byte size, and keep only the top entries for disk usage triage.
Reference arguments out of order with %2$ indices, repeat the previous value with the %< flag, and fail loudly on indices beyond the argument list.
A generic override gets a compiler-generated bridge method whose erased Object parameter delegates to the String version, visible via reflection.
Concatenate two gzip streams byte for byte and one GZIPInputStream reads both members back to back, because the format defines multi-member files.
Render raw bytes as offset, hex, and ASCII columns in fixed-width rows, the standard shape for inspecting wire protocols and files.
Parse literal IP addresses without DNS and classify them with isLoopback, isSiteLocal, and isAnyLocal probes for validation code.
Keep helper logic inside the interface with private methods: callable from default and static members, invisible to implementing classes, never inherited.
Split a token into three segments and Base64url-decode the header and payload so alg and claims can be inspected, without verifying the signature.
A label on the outer loop lets break and continue jump out of both levels at once: search terminates on first hit, continue skips the whole row.
Compare this inside an anonymous class with this inside a lambda: the anonymous instance names its own class, the lambda names the enclosing one.
Split a total across weighted shares with largest remainder allocation so the rounded parts always sum back to the total.
List.of builds unmodifiable snapshots that reject null elements and mutation, while Arrays.asList stays a fixed-size view and List.copyOf a real copy.
Case conversion changes meaning under the Turkish locale, so fixed words like protocol names must pin Locale.ROOT instead of trusting the default.
Locale.forLanguageTag parses BCP 47 tags and Locale.lookup picks the best match from user preferences, the same negotiation Accept-Language headers need.
Shift times past midnight wrap inside LocalTime: plusMinutes on 23:30 lands on 01:00 next cycle, minusHours before 00:00 rolls back into the evening.
Order lock acquisition by account id so opposite-direction transfers queue on the same locks instead of holding one and waiting for the other forever.
Split key=value pairs with a small scanner that honors double-quoted values containing spaces, keeping field order in a LinkedHashMap.
Set levels on loggers and handlers separately: a record must pass both gates, and setUseParentHandlers(false) stops duplicated parent output.
Reverse all 64 bits or just the eight bytes of a long with Long.reverse and Long.reverseBytes for bit-order and endianness conversions without loops.
Flatten a nested tree depth-first with a recursive mapMulti helper that feeds each node straight downstream without building intermediate lists.
Math.clamp bounds a value in one call, replaces nested max-min chains, and rejects an inverted range with IllegalArgumentException instead of guessing.
Math.round rounds half toward positive infinity while Math.rint rounds half to even, so 2.5 becomes 3 or 2 depending on the function a billing path picks.
Time code sections by subtracting two System.nanoTime calls: the origin is arbitrary, differences are the only meaningful reading, wall clocks drift.
Fold fullwidth Latin, superscript digits, and ligatures to base letters with NFKC before validating input, so length checks see real characters.
Format ranks as 1st, 2nd, 3rd with ordinal suffixes, handling the 11th/12th/13th exceptions that break the last-digit rule.
Submit a parallel stream to a dedicated ForkJoinPool so heavy aggregation stays isolated from the shared common pool.
Compile regex with Pattern.COMMENTS so whitespace and # comments become layout, keeping literal spaces via bracketed [ ] when needed.
PatternSyntaxException reports the failing index and a description, so a regex built from user input can reject bad patterns without guessing.
Period.between splits a date span into calendar years, months, and days while ChronoUnit.DAYS gives the total; month-end overflow clamps instead of throwing.
plusMonths and plusYears clamp to the last valid day instead of overflowing into the next month, and the clamp is not reversible when months are added back.
End a consumer loop by sending a sentinel object through the queue: the producer appends it after the last job and the consumer breaks on identity.
Guard mutable list state with a private final lock object instead of synchronized(this) so outside code cannot interfere with the monitor.
Capture subprocess stdout and stderr into separate files with Redirect.to, so logs survive waitFor and the two streams never interleave.
Draw bounded samples with Random.ints — origin inclusive, bound exclusive — and re-seeding with the same value replays the exact same sequence every run.
Random.nextGaussian draws mean-zero unit-variance samples; scale by sigma and shift by mean, or call the two-argument form added in Java 17.
Records generate equals and hashCode that compare array components by reference, so two identical int arrays never match; store a List instead.
Add secondary record constructors that delegate to the canonical one, deriving checkout dates and parsing ISO strings without breaking component accessors.
Pattern.CANON_EQ matches precomposed and decomposed accents as equal, so café with a combining mark still finds the precomposed pattern.
Class.getResourceAsStream strips a leading slash for classpath-root lookup, prepends the package for relative names, and returns null for missing resources.
An uncaught exception in a periodic task silently cancels it; wrapping the body in try/catch keeps the schedule alive after individual failures.
scheduleAtFixedRate keeps a steady start-time cadence while scheduleWithFixedDelay waits that long after each run, so task cost stretches the gap.
Wrap a record payload in a SealedObject under AES/GCM, then getObject with the key to reconstruct it from the stored algorithm parameters.
Serialize an invariant-bearing object through a serialization proxy so the constructor validation always runs on read.
Arithmetic right shift copies the sign bit so -8 stays negative, while unsigned shift fills zeros and turns the same bits into a huge positive.
TCP_NODELAY disables Nagle batching on a SocketChannel; getOption reads back the values the kernel actually accepted, not what was merely requested.
Loop read on a blocking SocketChannel until read() returns -1 for EOF, then echo back, with shutdownOutput closing the write half cleanly.
count() returns the known size without running a SIZED pipeline, so peek silently skips; filter destroys the size hint and forces the traversal.
Stream.toList returns an unmodifiable list while Collectors.toList stays mutable, so defensive copies depend on which terminal operator you pick.
StringBuilder starts at capacity 16, doubles plus two on overflow via ensureCapacity, and trimToSize hands the unused tail back when appending is done.
StringBuilder.reverse() treats each surrogate pair as one unit so emoji survive reversal, while a manual char-by-char loop splits them into lone surrogates.
StringWriter accumulates formatted text in memory and StringReader feeds it back through any Reader-based API, no temp files involved.
Pasted text hides U+200B and U+FEFF characters that trim and strip keep: drop code points whose Unicode category is FORMAT to clean them reliably.
Register a custom TemporalQuery on a formatter or parsed date to pull several typed fields in one pass, turning loose TemporalAccessor data into a small record.
Extract fields from fixed-width records with per-column start and end offsets, keeping short lines honest instead of throwing past the line end.
Split words into lines, then spread leftover spaces across every gap so all lines except the last hit the target width exactly.
Confine mutable state to one single-thread executor: every read and write is a submitted task, so no locks or atomic fields are needed.
Fields written by a worker thread become visible to the reader only after join returns: the happens-before edge needs no volatile or locks.
join(millis) returns silently on timeout without telling you which case happened: follow it with isAlive() to distinguish finished from still running.
Reuse a single pooled thread with and without ThreadLocal.remove: stale state leaks to the next borrower until remove re-runs withInitial.
prestartAllCoreThreads warms core threads and allowCoreThreadTimeOut lets idle ones exit after the keep-alive window, so the pool can shrink back to zero.
Turn a past Instant into human time ago labels, using Duration for minutes and hours and date arithmetic once a day has elapsed.
Refill tokens continuously from elapsed time and admit only when one is available, so bursts up to capacity pass while steady traffic stays capped.
Cut long text to a code point budget before appending an ellipsis, so surrogate pairs and CJK characters never split mid-character.
A return inside finally overrides the value from try and silently discards an in-flight exception, so cleanup blocks must never complete abruptly.
Two ArrayLists with different type arguments share one runtime class: the raw add bypasses checks and the cast failure surfaces at the typed read-back.
URLEncoder encodes query values with StandardCharsets.UTF_8 so spaces become plus signs and structural characters stay escaped in the query string.
Attach named user attributes to a file with UserDefinedFileAttributeView, read them back as bytes, and remove them with delete when superseded.
Build RFC 9562 version-7 UUIDs from a 48-bit millisecond timestamp so lexicographic order matches creation time, then verify compareTo follows the clock.
A varargs parameter compiles to an array argument: callers pass loose arguments, and an existing array slots in directly as the last parameter.
Splitting on dots and comparing each segment numerically fixes version ordering: 1.9 sorts before 1.10, which plain string comparison gets wrong.
Register every existing subdirectory up front and re-register on ENTRY_CREATE of a directory, because WatchService never watches new folders by itself.
Build cumulative weight bands on a TreeMap and hit them with ceilingEntry, so a random roll lands in the band its weight deserves.
Swap two elements through a private capture helper that accepts List<?> and re-types it to <T>, since wildcard captures cannot be named directly.
Zip STORED entries skip the deflater but the ZIP format demands size and CRC up front, so set both on the entry before writing its bytes.
Zip two lists by index into record pairs: the shorter side caps the length so uneven inputs clip instead of throwing IndexOutOfBounds.
ZoneRules resolve any instant to the real offset of a zone; fixed IDs like UTC+01:00 normalize to ZoneOffset, and zones come from the JDK's bundled IANA tzdb.
Arrays.asList on an int[] builds a one-element List<int[]> instead of boxing: pass an Integer[] (or IntStream.boxed) for element-wise conversion.
Arrays.parallelSort splits a large object array into sub-arrays sorted and merged across the ForkJoin common pool; small arrays fall back to TimSort.
Arrays.setAll fills an array from an index-based generator, and parallelSetAll splits the same job across threads when the fill is expensive.
updateAndGet and accumulateAndGet hand back the new value; getAndUpdate and getAndAccumulate return the old one. All four update atomically.
Peek ahead with mark and reset a BufferedReader to re-read characters after deciding how to parse them; exceeding readAheadLimit invalidates the mark.
Validate Java identifiers with Character.isJavaIdentifierStart and isJavaIdentifierPart; they accept letters, digits, underscore, dollar sign, Unicode letters.
A raw alias can smuggle an Integer into a plain List<String>, which only explodes on read; Collections.checkedList throws the ClassCastException at the insert.
Compare getName, getSimpleName and getCanonicalName across a plain class, a nested interface, an array and an anonymous class whose canonical name is null.
Strip edges and collapse whitespace runs with \s+ into single spaces before equality or dedup checks, noting which characters \s does not cover.
Collections.newSetFromMap turns any empty Map into a Set, inheriting the map ordering and concurrency: with a LinkedHashMap you get insertion-ordered sets.
One timed-out await puts a CyclicBarrier into the broken state: later awaiters get BrokenBarrierException immediately, and reset() clears it for the next round.
Wrap an InputStream in DigestInputStream so every chunk read feeds the MessageDigest, and confirm the streaming digest equals a one-shot update.
Escape the five HTML entities a text node needs (&, <, >, quotes) with a tiny switch, so user-provided strings can be embedded in markup safely.
Probe files with Files.isReadable, isWritable, and isExecutable; they return false on missing files instead of throwing, and executability is platform-specific.
Extend FilterReader to mask digits during reads; override the bulk read too because FilterReader forwards it to the underlying stream and would skip the mask.