Java how-to
Short ready-made solutions to common Java tasks with code examples.
Strings
- How to capitalize the first letterUpper-casing the first letter of a string in Java: substring, capitalizing every word and handling an empty string.
- How to check if a string contains a substringFinding a substring in Java: contains, indexOf, ignoring case and searching for one of several words.
- How to check if a string is a numberChecking whether a string is a number in Java: parseInt with exception handling, regular expressions and Character.isDigit.
- How to check if a string is a palindromeChecking for a palindrome in Java: StringBuilder.reverse, two pointers and phrases with punctuation.
- How to check if a string is empty or blankChecking whether a string is empty in Java: isEmpty, isBlank and protecting against null.
- How to check if a string starts or ends with somethingChecking the start and end of a string in Java: startsWith, endsWith, ignoring case and with an offset.
- How to compare strings correctlyComparing strings in Java: why not to use ==, and how equals, equalsIgnoreCase and compareTo work.
- How to compare strings ignoring caseCase-insensitive string comparison in Java: equalsIgnoreCase, compareToIgnoreCase and sorting.
- How to convert a string to a char array and backA string to a char array and back in Java: toCharArray, String.valueOf, chars() and sorting letters.
- How to convert a String to an int and backConverting a String to int, long and double in Java and back: parseInt, valueOf and handling bad input.
- How to convert camelCase to snake_case and backConverting camelCase to snake_case and back in Java with regular expressions.
- How to count occurrences of a character or substringCounting occurrences of a character and a substring in a Java string: chars(), indexOf in a loop and frequencies of all characters.
- How to count words in a stringCounting words in a Java string: splitting by whitespace, the empty string case and the frequency of each word.
- How to create a slug from a stringCreating a URL slug in Java: lower case, removing accents with Normalizer and replacing spaces with hyphens.
- How to encode and decode Base64Base64 encoding and decoding in Java: Base64.getEncoder, the URL-safe variant and UTF-8.
- How to extract numbers from a stringExtracting numbers from text in Java: Pattern and Matcher, results(), decimal and negative numbers.
- How to find matches with a regular expressionRegular expressions in Java: Pattern, Matcher, groups, named groups and replacing with groups.
- How to find the position of a substringFinding the position of a substring in Java: indexOf, lastIndexOf, finding all occurrences and cutting out a part.
- How to format a string with valuesFormatting strings in Java: String.format, formatted, width, alignment and numbers with precision.
- How to generate a random stringGenerating a random string in Java: SecureRandom for tokens, a custom alphabet and UUID.
- How to join strings with a separatorJoining strings in Java: String.join, Collectors.joining, StringJoiner and StringBuilder.
- How to mask part of a stringMasking a card number, phone number and email in Java with substring and repeat.
- How to remove all whitespace from a stringRemoving all spaces, tabs and line breaks from a Java string with replace and replaceAll.
- How to remove the last character of a stringRemoving the last character of a string in Java: substring, StringBuilder.deleteCharAt and dropping a trailing comma.
- How to replace text in a stringReplacing text in a Java string: replace, replaceAll with a regular expression, replaceFirst and replacing several words.
- How to reverse a stringReversing a string in Java with StringBuilder.reverse(), a loop, and with emoji in mind.
- How to split a stringSplitting a string in Java with split(): by a separator, by whitespace, with a limit and special characters.
- How to split text into linesSplitting multi-line text in Java with lines(), split, and handling different line breaks.
- How to trim whitespace from a stringRemoving whitespace from the ends of a string in Java: strip, trim, stripLeading and stripTrailing.
- How to truncate a stringTruncating a string in Java to a given length with an ellipsis, at a word boundary and without errors on short strings.
- How to validate an email addressValidating an email address in Java with a regular expression, and what to expect from such a check.
- How to write a multi-line stringMulti-line strings in Java: text blocks, indentation and inserting values with formatted.
Numbers
- How to calculate a factorialFactorial in Java: a loop, recursion, a stream and BigInteger for large values.
- How to calculate a percentagePercentages in Java: a percentage of a number, a share as a percentage, percentage change and integer division.
- How to calculate money in JavaHandling money in Java with BigDecimal: creating from a string, adding, multiplying, dividing and comparing.
- How to check if a number is evenChecking whether a number is even in Java: the remainder operator, negative numbers and the bitwise check.
- How to check if a number is primeChecking for a prime number in Java: trying divisors up to the square root, primes in a range and BigInteger.
- How to convert a double to an intConverting a double to an int in Java: casting, rounding, large values and NaN.
- How to convert a number to binary or hexNumber bases in Java: toBinaryString, toHexString, parseInt with a radix and HexFormat.
- How to detect integer overflowOverflow of int and long in Java: what happens, Math.addExact, multiplyExact and switching to long.
- How to format a number with thousands separatorsThousands separators in Java: String.format with the comma flag, NumberFormat and DecimalFormat.
- How to format a priceDisplaying an amount of money in Java: NumberFormat for currencies, the currency symbol, separators and locale.
- How to generate a random numberRandom numbers in Java: Random.nextInt in a range, decimals, a repeatable sequence and SecureRandom.
- How to limit a number to a rangeKeeping a number between a minimum and a maximum in Java: Math.clamp, Math.min and Math.max.
- How to pad a number with leading zerosLeading zeros in Java: String.format with the %05d pattern, order numbers and times.
- How to round a number to 2 decimal placesRounding to two decimal places in Java: Math.round, BigDecimal.setScale and formatting for output.
- How to round a number up or downRounding in Java: Math.ceil, Math.floor, Math.round, dropping the fractional part and negative numbers.
- How to use bit flagsBit flags in Java: power-of-two constants, setting, checking and clearing a bit with |, & and ~, and replacing flags with EnumSet.
- How to work with very large integersLarge integers in Java: the limits of int and long, BigInteger and its arithmetic.
Arrays
- How to add an element to an arrayAdding an element to a Java array: why the size is fixed, Arrays.copyOf, inserting in the middle and ArrayList.
- How to check if an array contains a valueFinding a value in a Java array: a loop, stream anyMatch, Arrays.asList.contains and binary search.
- How to compare two arraysComparing arrays in Java: Arrays.equals, deepEquals for nested arrays, mismatch and order-insensitive comparison.
- How to convert an array to a list and backArray to List and List to array in Java: Arrays.asList, List.of, new ArrayList, toArray and primitive arrays.
- How to copy an arrayCopying an array in Java: clone, Arrays.copyOf, copyOfRange, System.arraycopy and deep copies.
- How to fill an array with valuesFilling an array in Java: default values, Arrays.fill, Arrays.setAll and a range of numbers.
- How to find the max and min in an arrayThe maximum and minimum of an array in Java: a loop, IntStream.max, summaryStatistics and an array of objects.
- How to loop through an array with the indexIterating an array in Java: a for loop with an index, for-each, IntStream.range and iterating backwards.
- How to merge two arraysMerging arrays in Java: Arrays.copyOf with System.arraycopy, streams and merging without duplicates.
- How to print an arrayPrinting an array in Java: Arrays.toString, deepToString for 2D arrays, a custom format and a loop.
- How to reverse an arrayReversing an array in Java: swapping elements in a loop, Collections.reverse and List.reversed.
- How to sort an arraySorting an array in Java: Arrays.sort for numbers and strings, descending order, part of an array and by an object field.
- How to sum an array and find the averageThe sum and average of an array in Java: a loop, Arrays.stream().sum(), average() and overflow.
Collections
- How to build a simple LRU cacheA least-recently-used cache in Java based on LinkedHashMap and removeEldestEntry.
- How to check if a list contains an elementFinding an element in a Java list: contains, indexOf, anyMatch with a condition and fast checks with a HashSet.
- How to check if a map contains a keyChecking keys and values in a Map: containsKey, containsValue and why get is not always enough.
- How to compare two listsComparing lists in Java: equals with order, ignoring order and comparing contents as sets.
- How to count items by enum valueCounting by enum in Java: EnumMap with merge, groupingBy into an EnumMap, zeros for missing values and output order.
- How to count occurrences in a listCounting occurrences in a Java list: Collections.frequency, groupingBy with counting and Map.merge.
- How to create a listCreating a list in Java: ArrayList for a modifiable list, List.of for an unmodifiable one, and copying.
- How to create an immutable collectionImmutable collections in Java: List.of, Set.of, Map.of, List.copyOf and the difference from unmodifiableList.
- How to find common elements and the difference of two listsIntersection and difference of lists in Java: retainAll, removeAll and streams with a HashSet.
- How to find duplicates in a listFinding repeated elements in Java: Set.add, grouping with counting and checking whether there are duplicates.
- How to find the max and min in a listThe largest and smallest element of a list in Java: Collections.max, Stream.max, by an object field and an empty list.
- How to get a value from a map with a defaultDefault values in a Map: getOrDefault, putIfAbsent, computeIfAbsent and how they differ from get.
- How to get the first and last element of a listThe first and last element of a list in Java: getFirst and getLast from Java 21, get by index and an empty list.
- How to iterate over a mapIterating over a Map in Java: entrySet, forEach, keys or values only, and iteration order.
- How to merge two listsMerging lists in Java: addAll, Stream.concat, merging without duplicates and interleaving elements.
- How to merge two mapsMerging Maps in Java: putAll, merge for summing values and streams with a merge function.
- How to paginate a listPaginating a list in Java: subList, skip and limit, the number of pages and going out of bounds.
- How to remove an element from a listRemoving from a list in Java: remove by index and by value, removeIf with a condition and removing in a loop.
- How to remove duplicates from a listRemoving duplicates from a list in Java: LinkedHashSet, distinct(), uniqueness by a field and element order.
- How to reverse a listReversing a list in Java: Collections.reverse, List.reversed from Java 21 and reverse sort order.
- How to shuffle a listShuffling a list in Java: Collections.shuffle, repeatable shuffling and a random element.
- How to sort a list by multiple fieldsSorting by multiple fields in Java: thenComparing, a different order per field and null values.
- How to sort a list of objects by a fieldSorting a list of objects in Java: Comparator.comparing, descending order, by a string field and without changing the original list.
- How to sort a map by keySorting a Map by keys in Java: TreeMap, reverse order and sorting in a stream.
- How to sort a map by valueSorting a Map by value in Java: an entrySet stream, comparingByValue and LinkedHashMap to keep the order.
- How to split a list into chunksSplitting a list into fixed-size chunks in Java: subList in a loop and streams.
- How to swap keys and values in a mapInverting a Map in Java: toMap with swapped entries, repeated values and grouping keys.
- How to use a queue and a stackQueues and stacks in Java: ArrayDeque for FIFO and LIFO, PriorityQueue and why not to use the Stack class.
Stream API
- How to calculate the average of a listThe arithmetic mean in Java: average(), an empty list, the average of a field and by group.
- How to check if all elements match a conditionChecking elements in Java: allMatch, anyMatch, noneMatch and behaviour on an empty list.
- How to convert a list to a mapA list to a Map in Java: Collectors.toMap, Function.identity, duplicate keys and keeping the order.
- How to create a sequence of numbersNumber ranges in Java: IntStream.range, rangeClosed, iterate with a step and infinite streams.
- How to filter a listFiltering a list in Java: Stream.filter, several conditions, filtering by an object field and removeIf.
- How to find the first element matching a conditionFinding an element by condition in Java: filter with findFirst, working with Optional and a loop.
- How to flatten a list of listsFlattening nested lists in Java: flatMap, nested object fields and arrays.
- How to group a list by a fieldGrouping in Java with Collectors.groupingBy: lists per key, counting, mapping and sorted keys.
- How to join a list into a stringA list to a string in Java: String.join, Collectors.joining for numbers and objects, prefix and suffix.
- How to keep unique objects by a fieldUniqueness of objects by one field in Java: toMap with LinkedHashMap, a filter with a Set and a TreeSet with a comparator.
- How to split a list in two by a conditionSplitting a list into matching and non-matching elements in Java with Collectors.partitioningBy.
- How to sum a listThe sum of list elements in Java: mapToInt().sum(), summing an object field, BigDecimal and reduce.
- How to take the first N elementsThe first N elements in Java: limit, skip, subList and takeWhile.
- How to transform every element of a listTransforming list elements in Java: Stream.map, extracting a field, replaceAll and mapToInt.
Classes and objects
- How to check the type of an objectChecking types in Java: instanceof with a pattern, switch on types and getClass.
- How to convert a string to an enum and list its valuesWorking with enums in Java: valueOf, values, name, safe conversion and fields on constants.
- How to convert an object to JSON and backJSON in Java: the Jackson and Gson libraries, serializing records, reading JSON into an object and a list.
- How to copy an objectCopying objects in Java: a copy constructor, records, shallow and deep copies.
- How to create a builder for an objectThe builder pattern in Java: a nested Builder class, default values and checking required fields.
- How to create a singletonA singleton in Java: an enum with a single value, lazy initialization with a holder class and when you do not need one.
- How to create an immutable classImmutable objects in Java: records, final fields, defensive copies of collections and with-methods.
- How to implement equals and hashCodeequals and hashCode in Java: the rules, Objects.hash, records and what breaks in a HashSet without hashCode.
- How to make objects comparableThe Comparable interface in Java: compareTo, natural ordering, sorting and TreeSet.
- How to print an object in a readable formThe toString method in Java: why to override it, records, formatting and hiding secret fields.
Date and time
- How to add days to a dateDate arithmetic in Java: plusDays, minusDays, plusMonths, working days and the immutability of LocalDate.
- How to calculate age from a birth dateCalculating age in Java: Period.between, ChronoUnit.YEARS and a birthday on February 29.
- How to compare two datesComparing dates in Java: isBefore, isAfter, isEqual, compareTo, sorting and range checks.
- How to convert a time to another time zoneTime zones in Java: ZonedDateTime, withZoneSameInstant, ZoneId and daylight saving time.
- How to convert a timestamp to a dateUnix timestamps in Java: Instant.ofEpochSecond, milliseconds, converting to LocalDateTime and back.
- How to find the difference between datesThe difference between dates in Java: ChronoUnit.DAYS.between, Period for years and months, Duration for hours and minutes.
- How to format a dateFormatting a date in Java: DateTimeFormatter.ofPattern, pattern letters, month names and localized formats.
- How to format a duration in hours and minutesFormatting a duration in Java: Duration, toHoursPart, toMinutesPart and output like 01:05:09.
- How to get the current date and timeThe current date and time in Java: LocalDate.now, LocalDateTime.now, time zones and Instant.
- How to get the day of the weekThe day of the week in Java: getDayOfWeek, the name in a given language, the day number and weekend checks.
- How to get the first and last day of a monthThe start and end of a month in Java: withDayOfMonth, TemporalAdjusters, YearMonth and the number of days in a month.
- How to parse a date from a stringParsing a date from a string in Java: LocalDate.parse, a custom pattern, date and time, and error handling.
Files and I/O
- How to append text to a fileAppending to a file in Java: StandardOpenOption.APPEND, creating the file if missing and an event log.
- How to check if a file existsChecking a file in Java: Files.exists, isRegularFile, isDirectory, access rights and why a check does not replace error handling.
- How to copy or move a fileCopying and moving files in Java: Files.copy, Files.move, overwriting and renaming.
- How to create a folderCreating folders in Java: Files.createDirectories for nested folders, createDirectory and temporary folders.
- How to delete a file or folderDeleting in Java: Files.delete, deleteIfExists and deleting a folder with all its contents.
- How to get a file's extension and sizeA file's extension, name and size in Java: getFileName, lastIndexOf, Files.size and a readable size.
- How to list files in a folderListing files in Java: Files.list, recursive traversal with Files.walk, filtering by extension and sorting.
- How to read a .properties settings fileSettings files in Java: the Properties class, default values, numbers and environment variables.
- How to read a CSV fileReading CSV in Java: lines with Files.lines, splitting by comma, the header, records and the limits of manual parsing.
- How to read a file line by lineReading a file line by line in Java: Files.lines in try-with-resources, BufferedReader and line numbers.
- How to read a whole fileReading a file in Java: Files.readString, readAllLines, encoding and handling IOException.
- How to read command-line argumentsCommand-line arguments in Java: main with the args parameter, numbers, flags and checking the count.
- How to read user inputKeyboard input in Java: IO.readln from Java 25, Scanner, reading numbers and validating input.
- How to write a CSV fileWriting CSV in Java: the header, rows from objects, escaping quotes and commas.
- How to write text to a fileWriting to a file in Java: Files.writeString, writing a list of lines, BufferedWriter and overwriting a file.
Errors and exceptions
- How to avoid NullPointerExceptionNullPointerException in Java: where it comes from, how to read the message, null checks, Optional and default values.
- How to catch multiple exceptionsHandling several exceptions in Java: multiple catch blocks, multi-catch with a vertical bar, block order and finally.
- How to close resources automaticallytry-with-resources in Java: closing files and connections automatically, several resources and your own AutoCloseable.
- How to create a custom exceptionCustom exceptions in Java: extending RuntimeException or Exception, the message, the cause and extra fields.
- How to get an exception's stack trace as a stringStack traces in Java: printStackTrace into a StringWriter, getStackTrace, the top frame and logging.
- How to validate method argumentsValidating arguments in Java: IllegalArgumentException, Objects.requireNonNull, Objects.checkIndex and checks in records.
Concurrency
- How to add a timeout to a taskTask timeouts in Java: Future.get with a time limit, cancel and CompletableFuture.orTimeout.
- How to make a counter thread-safeRace conditions in Java: AtomicInteger, synchronized, ConcurrentHashMap.merge and why count++ is unsafe.
- How to pause executionDelays in Java: Thread.sleep, Duration, InterruptedException and running code on a schedule.
- How to run async tasks and combine their resultsCompletableFuture in Java: supplyAsync, thenApply, thenCombine, allOf and error handling with exceptionally.
- How to run tasks in parallelParallel tasks in Java: ExecutorService, submit and Future, invokeAll and closing the pool with try-with-resources.
- How to use virtual threadsVirtual threads in Java 21+: Thread.ofVirtual, Executors.newVirtualThreadPerTaskExecutor and thousands of concurrent tasks.
Miscellaneous
- How to connect to a database with JDBCConnecting to a database in Java: a JDBC driver, DriverManager.getConnection, URLs for PostgreSQL, MySQL and SQLite, closing the connection.
- How to exit a program with an exit codeExiting a program in Java: System.exit with a code, codes 0 and 1, leaving main with return, a shutdown hook and why not to call exit everywhere.
- How to generate a UUIDUUIDs in Java: UUID.randomUUID, parsing a string, checking the format and name-based UUIDs.
- How to hash a string (SHA-256, MD5)Hashing in Java: MessageDigest with SHA-256, hex output with HexFormat and why passwords are not stored this way.
- How to make an HTTP requestHTTP requests in Java with the built-in HttpClient: GET, POST with JSON, timeouts and the status code.
- How to measure execution timeMeasuring time in Java: System.nanoTime, Duration, Instant and why precise benchmarks need JMH.
- How to measure memory usageJVM memory in Java: Runtime.totalMemory, freeMemory and maxMemory, used memory before and after an operation, and why the numbers are approximate.
- How to read an environment variable with a default valueEnvironment variables in Java: System.getenv, a default value, numbers from variables, required variables and -D system properties.
- How to run a parameterized SQL query safelySQL parameters in Java with PreparedStatement: ? placeholders, setString and setInt, protection against SQL injection, a list of values in IN.
- How to run several SQL queries in one transactionTransactions in JDBC: setAutoCommit(false), commit and rollback, rolling back on an error and restoring the connection mode.