Format Milliseconds to hh:mm:ss in Java (Duration Examples)
Format milliseconds as hours, minutes and seconds text in Java with Duration toHours() and toMinutesPart(), with days, negatives and DurationFormatUtils.
Format milliseconds as hours, minutes and seconds text in Java with Duration toHours() and toMinutesPart(), with days, negatives and DurationFormatUtils.
Localized date format in Java with DateTimeFormatter, FormatStyle and Locale. Show timestamps in the user’s time zone and use ofLocalizedPattern().
Java arrays explained with memory layout, default values, rules and the Arrays class, plus every array tutorial grouped by task, from copy to conversion.
Learn why ArrayStoreException happens with covariant arrays, System.arraycopy() and toArray(), how to read its message, and how to fix and prevent it.
Calculate the sum and average of an array in Java with a loop or IntStream, and avoid integer division, int overflow and empty-array traps.
Convert list to array in Java with the three toArray() methods, get an int[] from a list of Integer, and turn arrays back into lists with asList().
Convert a Java stream to array form with toArray() and a generator, and arrays to streams with Arrays.stream(), including int[], ranges and 2D arrays.
Learn to remove an element from an array in Java by index, value or condition with System.arraycopy(), streams, ArrayList and ArrayUtils.
Convert int[] to Integer[] in Java with boxed() and back with mapToInt(), handle null elements, long, double and char arrays, and use ArrayUtils.
Learn to split an array in Java at an index, into halves, into fixed-size chunks or N parts with Arrays.copyOfRange(), loops and Java 24 gatherers.
Learn to concatenate two arrays in Java with System.arraycopy(), Arrays.copyOf(), streams, ArrayUtils and Guava, for primitive and object arrays.
Check if two arrays are equal in Java with Arrays.equals(), deepEquals(), mismatch() and compare(), and fix array equality in records, sets and tests.
Check if an array is sorted in Java by comparing neighbors, with noneMatch(), a Comparator, case-insensitive strings, ArrayUtils and Guava.
Find the top N elements in an array in Java by sorting a copy, with sorted().limit(), a PriorityQueue min-heap or Guava, for numbers and objects.
Find the max and min in an array in Java with one loop, IntStream max() and min(), summaryStatistics() or a Comparator, plus empty arrays and NaN.
Java arrays have a fixed length, so we resize an array by copying it into a new one with Arrays.copyOf(). Learn the default values, the alias trap, inserting with System.arraycopy(), resizing 2D arrays and when an ArrayList fits better.
Learn to reverse an array in Java in place with a swap loop, into a new array, with Collections.reverse() and List.reversed(), and avoid the int[] trap.
Learn to declare and initialize an array in Java with new, array initializers, Arrays.fill(), setAll(), streams and 2D arrays, plus all default values.
Learn some popular and the most used Java unit testing frameworks used for mocking the test dependencies and verifying the test results.
Java tutorial for beginners on Java 25. Install the JDK, run a first program and follow a 12-step learning path plus an index of every Java topic.
Sorting in Java for arrays, lists, maps, sets and streams with Comparable, Comparator chains, null handling, Collator and the common sorting mistakes.
A logging facade is an abstraction API that application code logs against, while a separate logging framework does the actual logging. SLF4J (Simple Logging Facade for Java) is the facade for logging frameworks such as Java Util Logging (JUL), Logback and Log4j2. We use the SLF4J API in the application …
A Mapped Diagnostic Context (MDC) is a per-thread map of key/value pairs that a logging framework adds to log messages, so we can distinguish the interleaved log output of different requests. Log output is interleaved when a server handles multiple clients at nearly the same time. 1. Stamping Requests with …
Learn Flogger fluent logging in Java with version 0.9, backends, rate limiting, lazy arguments and stack traces, compared with the SLF4J 2 fluent API.
Masking sensitive data in logback logs is done by partially or fully replacing the client-sensitive data or NPI (nonpublic personal information) with some arbitrary encoded text. For example, the SSN information can be replaced with all star characters or we can remove the complete SSN information from the logs. 1. …
Logback HTMLLayout outputs events in an HTML table. The content of the table columns is specified using a conversion pattern in the encoder property. 1. HTMLLayout Sample Configuration For quick reference, this is the configuration file we will be referring. It logs into c:/temp/logs/applicationLogs.html file and rolls-over daily. 2. Dependencies …
Logback RollingFileAppender appends log events into a file with the capability to rollover (archive the current log file and resume logging in a new file) based on a particular schedule, such as daily, weekly, monthly or based on log file size. For quick reference, this is configuration file we will …
Logback ConsoleAppender appends on the console though System.out or System.err print streams. In this Logback tutorial, learn about default configured console logging and how to apply custom configuration. 1. Dependencies Logback requires three modules in the application runtime i.e. logback-core, logback-classic and slf4j-api. The logback-classic module has implemented the SLF4J …
Set up Logback with one Maven dependency and a logback.xml file. Learn levels, additivity, rolling log files, MDC, async logging, conditions per environment and the fixes for common SLF4J and Logback errors.
Learn recursion in Java with call stack diagrams, base cases, factorial and Fibonacci examples, memoization and how to avoid StackOverflowError.
Learn to add default accessor methods (getter and setter) using Lombok and omit these methods for specific requirements. 1. Default Behavior Lombok provides two annotations to add getter and setter methods to a POJO. @Getter – can be applied on any field and class. When applied on a field, lombok …
Lombok @Builder generates a builder for our class, and Gson serializes and deserializes such a class without extra configuration, whereas Jackson serializes it directly but needs @Jacksonized or @JsonDeserialize to deserialize it. Serialization converts a Java object to JSON, and deserialization converts the JSON back to a Java object. We …
Lombok’s @Builder annotation is a useful technique to implement the builder pattern that aims to reduce the boilerplate code. In this tutorial, we will learn to apply @Builder to a class and other useful features. Ensure you have included Lombok in the project and installed Lombok support in the IDE. …
Learn to configure Log4j2 using Maven and Gradle dependencies. 1. Log4j Modules The main modules of interest are given below. We can read the complete list of modules and their dependencies at this link. 2. Maven Dependencies An example of log4j2 configuration with SLF4J using Maven. We can check the …
Learn to configure Log4j2 logging with SLF4J APIs. We will look at required dependencies, sample configuration and a demo to use the log statements. Read More: SLF4j Vs Log4j – Which One is Better? 1. Log4j2 and SLF4j Binding Dependencies To make Log4j2 work with SLF4J, we need to include …
Learn Java stream sort with null values using Comparator.nullsFirst() and nullsLast(), for null elements and null fields, and avoid the reversed() trap.
Learn to configure the Log4j2 provided JDBCAppender that writes log events to a relational database table using standard JDBC. The JDBCAppender obtains the database connection from a configured connection factory or JNDI datasource. Then it uses the provided column configuration to insert a new row in the log table, everytime …
Java new features from Java 8 to Java 27 in one place, with release dates, LTS versions, preview and final status per feature, and links to examples.
Measure JaCoCo code coverage for JUnit tests with Maven and Gradle, read the report, fail the build below a limit with the check goal and exclude classes.
Create a JUnit HTML report with the Maven Surefire Report plugin 3.6.0, mvn site or Gradle, read failures in it, and convert Open Test Reporting XML.
JUnit 5 conditional test execution by OS, Java version, system property, env variable or custom method, with JUnit 6 JRE changes and real skip reasons.
Control JUnit 5 test execution order with @TestMethodOrder, @Order, MethodName, Random seeds, custom orderers and @TestClassOrder, with JUnit 6 changes.
JUnit 5 timeout with @Timeout on tests, classes and lifecycle methods, thread modes, global defaults in junit-platform.properties and real failure output.
Write JUnit 5 parameterized tests with @ValueSource, @CsvSource, @MethodSource, @FieldSource and @ParameterizedClass, display names and JUnit 6 notes.
JUnit 5 @TempDir creates temporary directories for tests. Learn parameter, field and static scope, CleanupMode, TempDirFactory and JUnit 6.1 deletion.
Learn how the Java string constant pool works, why it is in the heap since Java 7, how String.intern() behaves and when string deduplication saves memory.
Create a Java enum with multiple values per constant, read them with getters, and find the constant from any value with a cached map and Optional.
Get object with max date from a Java list with Stream.max() and Comparator.comparing(). Covers min date, empty lists, null dates, ties and max per group.
Check if a date is a weekend in Java with DayOfWeek and EnumSet, support Friday-Saturday weekends, time zones and weekend pricing examples.
Since Spring 5, non-blocking Spring WebClient is a preferred alternative to blocking RestTemplate which is in maintenance mode/deprecated since then.
HowToDoInJava provides tutorials and how-to guides on Java and related technologies.
It also shares the best practices, algorithms & solutions and frequently asked interview questions.