DecimalFormat Pattern Grouping Rounding
Format numbers with explicit DecimalFormat patterns: grouping commas, fixed decimals, percent scaling, sign prefixes, and a declared rounding mode.
Page 28 of 50
Format numbers with explicit DecimalFormat patterns: grouping commas, fixed decimals, percent scaling, sign prefixes, and a declared rounding mode.
Wrap an interface implementation with Proxy.newProxyInstance so every method call is recorded first, the same trick frameworks use for auditing.
Model fixed option sets with EnumSet: noneOf, of, range, and complementOf build bit-packed sets of enum constants that iterate in declaration order.
Write equals and hashCode by hand on a plain class so equal objects land in the same HashSet bucket and contains finds them.
invokeAny races the same request across worker tasks, returns the first success, cancels the rest, and throws ExecutionException only when every task fails.
See what a saturated ThreadPoolExecutor does with new tasks: AbortPolicy throws RejectedExecutionException, CallerRunsPolicy runs the task in the submitter.
Try-with-resources manages executor shutdown: ExecutorService.close blocks until every submitted task finishes, replacing the manual shutdown sequence.
Removing from an ArrayList inside for-each trips ConcurrentModificationException; Iterator.remove and removeIf delete through the cursor safely.
Append to a log through FileChannel and call force(true) so data and metadata reach the device before the caller returns, surviving a process crash.
FileChannel.read into a ByteBuffer array scatters bytes across buffers in order, letting one call fill a length field and its payload without copying.
transferTo hands bytes between channels without a user-space buffer; a call may move fewer bytes than requested, so the loop advances by the returned count.
Search a directory tree lazily with Files.find, pairing a glob PathMatcher with file attributes and a depth cap instead of walking every node.
Fetch size, type, and timestamps in one Files.readAttributes call so upload probes avoid several separate filesystem stat round trips.
Control Files.writeString with CREATE_NEW, CREATE, APPEND, and TRUNCATE_EXISTING so overwrites, appends, and fail-on-existing behavior stay explicit.
Read total, unallocated, and usable space from the volume holding the working directory so a disk-full condition becomes a planned degradation.
Order function application deliberately: compose runs its argument first, andThen runs it second, and chaining both builds a normalization pipeline.
cancel(true) sends an interrupt to a running Future's worker thread and marks the task cancelled, after which get() throws CancellationException forever.
Read configuration from System.getenv with explicit fallbacks, because getenv returns null for missing variables and the map itself is read-only.
Compress bytes with GZIPOutputStream and read them back with GZIPInputStream, verifying a byte-exact roundtrip and the failure path for non-gzip input.
Compute union, intersection, and difference over HashSet with addAll, retainAll, and removeAll so tag comparisons run without hand-written loops.
Format bytes as delimited hexadecimal and parse them back with HexFormat; uppercase, prefix, and separator are configurable and bad input fails fast.
Sign a payload with the JCA Mac under HmacSHA256 and verify by recomputing the tag through HexFormat; any changed byte flips the tag and fails the comparison.
Store keys by reference instead of equals: two distinct String instances with the same characters occupy two entries in an IdentityHashMap.
Bind matched values directly with instanceof type patterns: the variable is in scope in the same condition and flows through null-safe checks.
Measure with Instant and Duration: capture the start, compare elapsed against a budget with compareTo, and report toMillis instead of hand-rolled math.
Use bitCount, rotateLeft, highestOneBit, and lowestOneBit for popcount, circular shifts, and power-of-two rounding without manual loops.
Autoboxed values from -128 to 127 are cached, so == compares the same object inside the range but distinct objects once boxing exceeds it.
When two interfaces supply the same default method, the implementing class must override it and pick a side with InterfaceName.super.method().
Generate numeric pipelines with IntStream.range and iterate, mixing primitive sum with boxed collectors and index-based array access in one pass.
Write a manifest into a jar with JarOutputStream and read its attributes back with JarFile, the metadata version reporting relies on.
Wrap an expensive initializer in a memoized Supplier so the value is computed on first get and reused afterwards without re-running the loader.
Hand items to a consumer with LinkedTransferQueue transfer, which blocks until the item is taken, while tryTransfer fails fast when nobody waits.
Deduplicate while keeping first-seen order: HashSet scrambles iteration, LinkedHashSet remembers insertion, and re-adding an element never moves it.
Split a list into fixed-size batches with subList windows so bulk calls respect API limits; each batch is a read-only view of the backing list.
Match an Accept-Language header against supported locales: Locale.filter returns all matches, Locale.lookup picks the single best one by weight.
Parse BCP 47 tags into Locale objects with forLanguageTag, build canonical tags back with Locale.Builder, and watch ill-formed tags resolve to und.
Turkish uppercases i to dotted İ: use Locale.ROOT or equalsIgnoreCase for keys and protocol tokens, never the machine default locale.
Map.copyOf and Set.copyOf freeze a snapshot, while Collections.unmodifiableMap stays a live view that tracks the source, and both reject every write.
Map a file into memory with FileChannel.map and read it as a MappedByteBuffer, so large files are scanned without copying through heap buffers.
User-supplied replacement text containing $ or backslash throws in replaceAll; Matcher.quoteReplacement escapes both so substitution stays literal.
Build replacement text from a MatchResult inside the function form of replaceAll, so dollar signs in untrusted input can never trigger template expansion.
Catch integer overflow when it happens: addExact, multiplyExact, negateExact, and toIntExact throw ArithmeticException instead of wrapping silently.
Clamp values into a range with the Java 21 Math.clamp overloads: long-to-int narrowing never overflows, and min greater than max is rejected outright.
Tell truncating division and floor division apart: % keeps the dividend sign while Math.floorMod always lands in 0..divisor-1, ideal for circular indexing.
Build user-facing messages with MessageFormat placeholders so numbers and dates render per Locale, and single quotes need doubling to stay literal.
parse() silently ignores trailing garbage; the ParsePosition overload returns null on failure and exposes getIndex and getErrorIndex so bad input is rejected.
Attach an ObjectInputFilter allowlist before readObject so only approved classes are rebuilt; anything else fails fast as InvalidClassException.
Give nullable values explicit fallbacks with requireNonNullElse, requireNonNullElseGet, and Objects.toString so the default is stated at the call site.
orElse evaluates its argument even on a cache hit, while orElseGet invokes the supplier only when the Optional is empty.
parallelStream splits work across the common pool: forEach drops encounter order, forEachOrdered restores it, while sum and findFirst stay deterministic.
Parse CLI numbers defensively: wrap parseInt in try/catch, reject blanks and out-of-range ports, and return OptionalInt instead of leaking exceptions.
Derive the relative path between two locations with relativize and anchor it back with resolve; mixing absolute and relative inputs throws.
Wrap untrusted strings with Pattern.quote before compiling so regex metacharacters match literally instead of throwing or widening the match.
Tokenize heterogeneous input lazily with splitAsStream and filter collections with Pattern.asPredicate instead of splitting whole strings into arrays.
Build compound filters from small predicates with and, or, and negate, so each rule stays a one-line test that reads like the requirement.
Drain a PriorityBlockingQueue by priority: elements with the highest comparator order come out first, and take blocks while the queue is empty.
Read the JVM itself through ProcessHandle.current(): pid, command, start time, and child processes, with every detail wrapped in Optional.
Round-trip service configuration through Properties store and load, with getProperty's two-arg form supplying defaults for absent keys.
List built-in generator algorithms, select one by name, and prove same-seed reproducibility so tests and replays stay deterministic.
Bound lock waits with ReentrantLock.tryLock(timeout): give up instead of blocking forever while another thread holds the lock, unlocking only on success.
Match a repeated word with a backreference: \1 re-captures group one inside the pattern and $1 reuses it in replaceAll to collapse duplicates.
MULTILINE re-anchors ^ and $ per line, CASE_INSENSITIVE folds letter case, DOTALL lets dot cross newlines; flags combine with bitwise OR.
Greedy patterns grab to the last delimiter, reluctant ones stop at the first, and possessive ones never give back, so catastrophic backtracking cannot happen.
Validate several password rules with zero-width lookahead and slice dollar amounts with lookbehind, checking positions without consuming input characters.
Extract structured fields from log lines and email addresses with named capturing groups, reading each match by name instead of fragile numbered group indexes.
Point Scanner at any string or stream, swap its delimiter for a regex, and pull typed tokens with nextInt, which throws on non-numeric input.
Draw the same sample sequence on every run by seeding Random explicitly, the property test fixtures and example data need to be stable.
Use reversed(), getFirst, and getLast from the JDK 21 SequencedCollection interfaces so order-sensitive access no longer needs size-minus-one index arithmetic.
Walk the stack lazily for audit logs: filter frames to the nearest non-self caller, or read the direct caller class with RETAIN_CLASS_REFERENCE.
Reshape streams with JDK 24 Gatherers: windowFixed batches elements into fixed-size lists and fold reduces a stream to a single accumulated value.
Walk cursor-paginated APIs with the three-argument Stream.iterate, where the hasNext predicate ends the sequence exactly when the next token is null.
Fold a stream to one value three ways: with identity, as Optional without identity, and in parallel where the combiner merges partial sums.
Build case-insensitive key lookups with String.CASE_INSENSITIVE_ORDER: a TreeMap treats differently-cased duplicates as one key, so headers match any spelling.
Shift every line of a runtime-built multi-line string with indent, then recover messy indentation with stripIndent, which strips the smallest common indent.
String.split treats its argument as a regex: dots swallow whole strings, trailing empties vanish by default, and a negative limit is what preserves them.
subList hands back a live view: clearing it removes from the backing list, while structural edits to the backing list invalidate the view and throw.
Push readings through SubmissionPublisher, whose subscriber pulls items and exposes a future that completes only after everything is consumed.
Return values directly from switch expressions with arrow labels and yield, gaining exhaustive enum checking without default branches or fall-through.
Hand work straight from producer to consumer with a zero-capacity queue: put() blocks until another thread takes, so nothing is buffered in between.
Log through the JDK built-in System.Logger facade: zero dependencies, MessageFormat-style placeholders, and Supplier messages built only when the level is on.
Read built-in properties, supply defaults for absent keys, and mutate values at runtime — unlike environment variables, properties are writable.
TemporalAdjusters turns business rules like next Friday, last day of month, or first Monday into single with() calls on immutable LocalDate values.
Walk a thread through NEW, RUNNABLE, TIMED_WAITING, and TERMINATED with getState, the states thread dumps report for stuck workers.
Name pool threads through a ThreadFactory so thread dumps and logs identify workers: fixed pools spawn one named thread per task until core size.
Route exceptions escaping a raw thread to the default uncaught exception handler, and see why pooled submit() tasks keep theirs hidden inside the Future.
Encode every key and value with URLEncoder before joining the query string: form rules turn spaces into + and escape &, and URLDecoder reverses it.
Generate random UUIDv4 identifiers with randomUUID, parse canonical text back with fromString, and rely on fromString rejecting malformed input.
Give a plain field atomic operations through a VarHandle: compareAndSet fails on stale expectations and getAndAdd returns the value it replaced.
A volatile flag gives the worker loop a fresh read of shared state every iteration, so a writer thread stops it promptly instead of never.
Coordinate threads on one monitor with wait and notifyAll inside a synchronized guarded block that rechecks its condition in a while loop.
Delete a whole directory tree with Files.walkFileTree and a SimpleFileVisitor, clearing every file before each directory in postVisitDirectory.
Week boundaries differ by locale: WeekFields exposes the first day, minimal-days rule, and week numbering so calendar buckets match user expectations.
Validate card expiry printed as MM/yy with YearMonth.parse: the printed month stays valid through its last day, so only earlier months count as expired.
Open a zip archive as a filesystem with FileSystems.newFileSystem so Path APIs list and read entries without unpacking the archive first.
DST gaps shift forward with atZone and overlaps default to the earlier offset; withLaterOffsetAtOverlap pins the other side of a repeated wall-clock time.
A visually hidden aria-live region announces async outcomes to screen readers; clear it before writing so repeated messages are spoken again.
Await a one-shot event with events.once instead of wiring resolve callbacks by hand, and pass an AbortSignal so a listener that never fires cannot hang.
Disable a whole form with one fieldset.disabled flag during submission, and release it in finally so a failed gateway never leaves the form locked.
filter(Boolean) drops every falsy entry, including 0 and empty strings; an explicit predicate keeps legal zeros and reads clearly at review time.
Move an item to a new index with two splice calls in place, or rebuild with slices immutably; same-slot moves and past-end targets stay predictable.