How do I check if a string contains only digits in Java?

Use String.matches() with the regular expression [0-9]+ to check whether a string contains one or more digits from 0 to 9.

In this example, you will check several strings, including a code with leading zeros, a decimal number, and an empty string.

Source code

Save the following code as DigitsOnlyExample.java:

public class DigitsOnlyExample {
    void main() {
        String[] inputs = {"123", "007", "12a3", "-42", "3.14", " 123 ", ""};

        for (String input : inputs) {
            boolean digitsOnly = input.matches("[0-9]+");
            IO.println("\"" + input + "\": " + digitsOnly);
        }
    }
}

Explanation

The matches() method checks whether the entire string matches the regular expression:

boolean digitsOnly = input.matches("[0-9]+");

The expression has two parts:

Part Meaning
[0-9] Matches one digit from 0 to 9
+ Requires one or more matches

The string "007" matches because leading zeros are allowed. The string "12a3" fails because it contains a letter. Signs, decimal points, and spaces also cause the check to fail.

An empty string fails because + requires at least one digit. Use [0-9]* if an empty string should also pass.

Run the example

Compile and run the file:

javac DigitsOnlyExample.java
java DigitsOnlyExample

Output

"123": true
"007": true
"12a3": false
"-42": false
"3.14": false
" 123 ": false
"": false

The pattern [0-9]+ checks the text without converting it to a number. For example, it accepts "007" as written, and it can match a string whose numeric value is too large for an int.

If your input may contain decimal digits from other scripts, use "\\p{Nd}+" instead. That pattern also accepts digits such as "١٢٣".

How Do I Set Up Hibernate ORM 7 in a Maven Project?

In article 1, we introduced a Book entity and showed what Hibernate does when you persist an object. Now we will create a complete Maven application that saves that book to H2 and loads it again through Jakarta Persistence.

We will keep the same package, title, and manually assigned identifier. Author and Publisher relationships will come later in the roadmap; this article establishes the runnable project they will use.

1. Prepare Java and Maven

Install JDK 25 and Maven 3.9 or later. Check that Maven uses JDK 25:

java -version
mvn -version

This example uses Hibernate ORM 7.4.17.Final, released November 19, 2026, the latest stable release verified on November 23, 2026. It updates Week 01’s 7.4.15.Final within the same release series. The official compatibility matrix lists Java 25 and Jakarta Persistence 3.2. H2 2.5.252 is listed on the official H2 download page.

2. Create the Maven project

Create a directory named hibernate-book-catalog. Inside it, create the files below. Paths are relative to this directory.

File: pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.kodejava</groupId>
    <artifactId>hibernate-book-catalog</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.release>25</maven.compiler.release>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.hibernate.orm</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>7.4.17.Final</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>2.5.252</version>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.14.1</version>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>3.6.3</version>
                <configuration>
                    <mainClass>org.kodejava.hibernate.BookCatalogApp</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Hibernate Core supplies the ORM implementation and brings in Jakarta Persistence transitively. H2 supplies the JDBC driver at runtime. The compiler plugin targets Java 25; the execution plugin runs our main class with the project’s dependencies.

3. Add the Book entity

File: src/main/java/org/kodejava/hibernate/Book.java

package org.kodejava.hibernate;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "books")
public class Book {
    @Id
    private Long id;

    @Column(nullable = false)
    private String title;

    protected Book() {
    }

    public Book(Long id, String title) {
        this.id = id;
        this.title = title;
    }

    public String getTitle() {
        return title;
    }
}

This is the entity introduced in article 1. Mapping annotations are on fields, so Hibernate accesses fields directly. A setter is not required for loading the title. The protected no-argument constructor allows the persistence provider to instantiate the entity. For now, the application assigns 1L as the identifier.

4. Configure the persistence unit

File: src/main/resources/META-INF/persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="https://jakarta.ee/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_2.xsd"
             version="3.2">
    <persistence-unit name="book-catalog" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>org.kodejava.hibernate.Book</class>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <properties>
            <property name="jakarta.persistence.jdbc.driver" value="org.h2.Driver"/>
            <property name="jakarta.persistence.jdbc.url" value="jdbc:h2:mem:book_catalog"/>
            <property name="jakarta.persistence.jdbc.user" value="sa"/>
            <property name="jakarta.persistence.jdbc.password" value=""/>
            <property name="jakarta.persistence.schema-generation.database.action" value="drop-and-create"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
        </properties>
    </persistence-unit>
</persistence>

A persistence unit groups entity mappings and connection settings under one name. We explicitly register Book and disable discovery of unlisted entities so that the model is easy to follow.

RESOURCE_LOCAL means our application controls transactions through EntityTransaction. The H2 URL creates a named database in memory. Hibernate’s connection pool keeps connections available during the application; the database disappears when its last connection closes. Nothing is saved to a database file.

drop-and-create recreates the mapped schema when the persistence unit starts. Use it only for this disposable example: it can delete existing tables and data. Later, we will manage persistent schema changes with migrations. Hibernate detects the H2 SQL dialect from JDBC metadata, so no explicit dialect setting is needed.

The bootstrap and configuration approach follows Hibernate’s Jakarta Persistence quickstart.

5. Save and load a book

File: src/main/java/org/kodejava/hibernate/BookCatalogApp.java

package org.kodejava.hibernate;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityTransaction;
import jakarta.persistence.Persistence;

public class BookCatalogApp {
    public static void main(String[] args) {
        try (EntityManagerFactory factory =
                     Persistence.createEntityManagerFactory("book-catalog")) {
            saveBook(factory);
            loadBook(factory);
        }
    }

    private static void saveBook(EntityManagerFactory factory) {
        try (EntityManager entityManager = factory.createEntityManager()) {
            EntityTransaction transaction = entityManager.getTransaction();
            try {
                transaction.begin();
                entityManager.persist(new Book(1L, "Effective Java"));
                transaction.commit();
                System.out.println("Saved book: Effective Java");
            } catch (RuntimeException exception) {
                if (transaction.isActive()) {
                    transaction.rollback();
                }
                throw exception;
            }
        }
    }

    private static void loadBook(EntityManagerFactory factory) {
        try (EntityManager entityManager = factory.createEntityManager()) {
            Book book = entityManager.find(Book.class, 1L);
            if (book == null) {
                throw new IllegalStateException("Book 1 was not found");
            }
            System.out.println("Loaded book: " + book.getTitle());
        }
    }
}

Persistence.createEntityManagerFactory() finds META-INF/persistence.xml on the classpath and selects the unit named book-catalog. Create one factory for the application and close it at shutdown. Each EntityManager represents a separate persistence context and must also be closed. Jakarta Persistence 3.2 supports try-with-resources for both.

The write runs inside a transaction. Committing flushes the insert to H2. If the operation fails and the transaction is still active, we roll it back and propagate the failure.

The read uses a new entity manager, so it does not reuse the original persistence context’s managed book. A primary-key find() outside a transaction is permitted here because we are simply reading without a lock. In larger applications, transaction boundaries should follow the complete unit of work.

6. Run the application

From the directory containing pom.xml, run:

mvn clean compile exec:java

Maven downloads dependencies, compiles both Java files, copies resources into target/classes, and runs BookCatalogApp.

Expected application output:

Saved book: Effective Java
Loaded book: Effective Java

Hibernate also prints startup messages and SQL. Formatting may vary, but the SQL includes table creation, an insert, and a select:

create table books (
    id bigint not null,
    title varchar(255) not null,
    primary key (id)
)
insert into books (title, id) values (?, ?)
select b1_0.id, b1_0.title from books b1_0 where b1_0.id=?

Question marks are JDBC bind parameters, not missing values. Running the command again starts with a fresh in-memory database, so the assigned ID does not collide with a previous run.

If startup reports that no persistence provider exists for book-catalog, check the exact filename, the META-INF directory, the persistence-unit name, and the Hibernate dependency. If compilation reports that release 25 is unsupported, check the JDK shown by mvn -version. A warning about Hibernate’s built-in connection pool is expected for this small tutorial; production applications should configure a production connection pool.

Maven Dependencies

These are all direct library dependencies needed by this example. The complete POM above also pins the build plugins. Jakarta Persistence is supplied transitively by Hibernate Core; no separate driver installation or H2 server is required.

<dependencies>
    <dependency>
        <groupId>org.hibernate.orm</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>7.4.17.Final</version>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>2.5.252</version>
        <scope>runtime</scope>
    </dependency>
</dependencies>

How do I model parsing success and failure with a sealed interface in Java 21?

When a user enters a number, your program needs to handle both valid and invalid input. Returning null on failure loses the reason for the error. Instead, you can return an object that represents either a parsed value or a helpful message.

This tutorial builds a small result model using a sealed interface, two records, and a pattern-matching switch.

1. Define the possible outcomes

Our parser returns a ParseResult. Its sealed declaration lists exactly two permitted implementations:

  • Success, containing an integer.
  • Failure, containing an error message.

This makes the possible outcomes visible in the type definitions.

2. Parse input at the application boundary

Before parsing, check for null or blank input. For other strings, remove surrounding whitespace and call Integer.parseInt().

Catch NumberFormatException inside the parser and convert it into a Failure. The caller can then handle both outcomes through the same return type.

3. Handle each outcome with a switch

A record pattern such as Success(int value) extracts the component into a local variable. Java 21 supports record patterns in switches. See Java’s record pattern documentation.

Because the switch covers both permitted implementations, it needs no default. If you later add another result type, recompiling this switch helps reveal the missing case. See pattern matching for switch.

4. Run the complete example

Save this code as ParseResultExample.java:

public class ParseResultExample {
    sealed interface ParseResult permits Success, Failure { }

    record Success(int value) implements ParseResult { }

    record Failure(String message) implements ParseResult { }

    static ParseResult parse(String input) {
        if (input == null || input.isBlank()) {
            return new Failure("Enter a whole number");
        }

        try {
            return new Success(Integer.parseInt(input.strip()));
        } catch (NumberFormatException exception) {
            return new Failure("Invalid or out-of-range integer");
        }
    }

    static String describe(ParseResult result) {
        return switch (result) {
            case Success(int value) -> "Parsed: " + value;
            case Failure(String message) -> "Error: " + message;
        };
    }

    public static void main(String[] args) {
        String[] inputs = {
                " 42 ", "hello", "2147483648", null
        };

        for (String input : inputs) {
            System.out.println(describe(parse(input)));
        }
    }
}

Compile and run:

javac --release 21 ParseResultExample.java
java ParseResultExample

Output:

Parsed: 42
Error: Invalid or out-of-range integer
Error: Invalid or out-of-range integer
Error: Enter a whole number

The third input contains valid digits but exceeds the maximum int value, 2147483647. It therefore follows the same failure path as invalid text. The accepted range and exception behavior are documented in Integer.parseInt().

Best practices

  • Return a result object for every expected outcome; keep null out of the result contract.
  • Catch the specific parsing exception rather than a broad Exception.
  • Use separate failure types when callers need different recovery actions.
  • Keep presentation separate from parsing, as the describe() method does here.
  • Remember that default does not handle a null switch selector. This parser always returns a non-null result.

Summary

A sealed result model makes success and failure explicit. Records carry the associated data, while an exhaustive switch gives callers a clear place to handle every outcome.

How do I format a date using DateTimeFormatter in Java?

Use DateTimeFormatter to turn a LocalDate into text. You can choose the order of the day, month, and year, and use a locale to control the language of the month name.

In this example, you will format the same date in two ways: 11/11/2026 and 11 November 2026.

Source code

Save the following code as DateFormattingExample.java:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class DateFormattingExample {
    void main() {
        LocalDate date = LocalDate.of(2026, 11, 11);

        DateTimeFormatter numericFormat =
                DateTimeFormatter.ofPattern("dd/MM/uuuu");
        DateTimeFormatter longFormat =
                DateTimeFormatter.ofPattern("d MMMM uuuu", Locale.ENGLISH);

        IO.println("Numeric date: " + date.format(numericFormat));
        IO.println("Date with month name: " + date.format(longFormat));
    }
}

Explanation

LocalDate.of(2026, 11, 11) creates a date using the year, month, and day in that order. A LocalDate stores a calendar date without a time or time zone.

The ofPattern() method creates a formatter from a pattern. The letters are case-sensitive:

Pattern Meaning Example
d Day of the month without zero padding 5
dd Day of the month padded to two digits 05
MM Month number padded to two digits 03
MMMM Full month name March
uuuu Calendar year, padded to at least four digits 2026

Slashes and spaces in these patterns appear as written. Locale.ENGLISH makes the full month name appear in English regardless of the system’s default locale.

The date.format(...) call returns a string. You can format the same date in multiple ways because formatting leaves the LocalDate unchanged.

Use uuuu for the calendar year in these patterns. Uppercase YYYY means the week-based year, which can differ from the calendar year near the start or end of a year.

Run the example

Compile and run the file:

javac DateFormattingExample.java
java DateFormattingExample

Output

Numeric date: 11/11/2026
Date with month name: 11 November 2026

To see the difference between d and dd, change the date to LocalDate.of(2026, 3, 5). The numeric format displays 05/03/2026, and the format with the month name displays 5 March 2026.

How do I create an animated moiré pattern in Java Swing?

You can create a moiré pattern by drawing two sets of parallel lines on top of one another and rotating one set slightly. Their spacing produces broad bands that appear to move as the angle changes.

Rotating Moire

Rotating Moire

This SwingLoops example uses Java Swing and Java 2D to animate the effect. It requires no external libraries or image assets.

Source code

Save the following code as RotatingMoire.java:

package org.kodejava.swing.animation;

import java.awt.*;
import java.awt.geom.Line2D;
import javax.swing.*;

public class RotatingMoire extends JPanel {
    private static final int WIDTH = 450;
    private static final int HEIGHT = 800;
    private static final int EXTENT = 700;
    private static final int SPACING = 11;
    private static final double CYCLE = 12.0;

    private final Timer timer = new Timer(16, _ -> repaint());
    private long startedAt;
    private int mode = 3;

    public RotatingMoire() {
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        setBackground(new Color(9, 16, 29));

        for (int i = 1; i <= 3; i++) {
            final int selected = i;
            String action = "mode" + i;
            getInputMap(WHEN_IN_FOCUSED_WINDOW).put(
                    KeyStroke.getKeyStroke((char) ('0' + i)), action);
            getActionMap().put(action, new AbstractAction() {
                @Override
                public void actionPerformed(
                        java.awt.event.ActionEvent event) {
                    mode = selected;
                    repaint();
                }
            });
        }
    }

    @Override
    public void addNotify() {
        super.addNotify();
        startedAt = System.nanoTime();
        timer.start();
    }

    @Override
    public void removeNotify() {
        timer.stop();
        super.removeNotify();
    }

    private static void layer(Graphics2D parent,
                              double angle, Color color) {
        Graphics2D g = (Graphics2D) parent.create();
        try {
            g.rotate(angle);
            g.setColor(color);
            g.setStroke(new BasicStroke(3.5f));
            for (int x = -EXTENT; x <= EXTENT; x += SPACING) {
                g.draw(new Line2D.Double(
                        x, -EXTENT, x, EXTENT));
            }
        } finally {
            g.dispose();
        }
    }

    @Override
    protected void paintComponent(Graphics graphics) {
        super.paintComponent(graphics);
        Graphics2D g = (Graphics2D) graphics.create();

        try {
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);

            double scale = Math.min(
                    getWidth() / (double) WIDTH,
                    getHeight() / (double) HEIGHT);
            g.translate(getWidth() / 2.0, getHeight() / 2.0);
            g.scale(scale, scale);
            g.clipRect(-WIDTH / 2, -HEIGHT / 2, WIDTH, HEIGHT);

            double seconds = (System.nanoTime() - startedAt) / 1e9;
            double phase = 2 * Math.PI * (seconds % CYCLE) / CYCLE;
            double movingAngle = Math.toRadians(
                    10 + 7 * Math.sin(phase));

            layer(g, 0, new Color(62, 202, 226, 180));

            if (mode >= 2) {
                layer(g, mode == 2 ? Math.toRadians(10) : movingAngle,
                        new Color(244, 166, 123, 180));
            }
        } finally {
            g.dispose();
        }
    }

    static void main() {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("SwingLoops - Rotating Moire");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(new RotatingMoire());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}

Run the example

With a JDK 25 installed, open a terminal in the directory containing the source file:

javac RotatingMoire.java
java RotatingMoire

A desktop environment is required to display the Swing window. Close the window to stop the application.

Use these keys while the window is active:

Key View
1 Show only the fixed cyan lines.
2 Add a stationary second layer at 10 degrees.
3 Animate the second layer.

Draw the two layers

The layer() method draws equally spaced vertical lines. Each line has the same width and extends beyond the visible canvas.

Before drawing the second layer, the code rotates its copied graphics context:

g.rotate(angle);

Java 2D transforms all subsequent line coordinates. The method disposes the copied context afterward, so its rotation does not affect the other layer.

The broad bands are not separate shapes. They emerge where the two repeating line patterns overlap.

Why do broad bands appear?

When two line grids have similar orientations, their relative alignment changes slowly across the image. Some regions contain closely aligned lines; elsewhere, the lines separate and cross. This creates a larger repeating pattern over the fine line structure.

For two ideal grids with the same spacing s and an angle difference θ, the moiré spacing is approximately:

D = s / (2 × sin(θ / 2))

Angles in this formula are in radians. As the angle difference becomes smaller, the broad bands become farther apart.

For example, with a line spacing of 11 pixels and an angle difference of 10 degrees, the idealized band spacing is about 63 pixels. Stroke width, transparency, and the screen’s sampling affect the final appearance.

This example deliberately constructs the effect from two layers. It is different from unwanted aliasing caused solely by insufficient display resolution, although resizing can introduce additional sampling effects.

Animate the rotation

The rotating layer follows this angle:

double movingAngle = Math.toRadians(
        10 + 7 * Math.sin(phase));

Sine varies from −1 to 1, so the angle varies smoothly between 3 and 17 degrees. Keeping it away from zero avoids the extremely wide band spacing near perfect alignment.

The time phase completes one turn every 12 seconds:

double phase = 2 * Math.PI * (seconds % CYCLE) / CYCLE;

At the cycle boundary, the angle returns to its starting value with matching motion, allowing the animation to repeat smoothly.

Paint safely with Swing

A Swing timer requests repaints approximately every 16 milliseconds. Actual repaint frequency depends on the event queue and system performance.

The angle uses elapsed time rather than a frame counter, so delayed frames do not change the intended cycle duration. The interface, timer callbacks, and painting run on Swing’s event-dispatch thread.

The drawing is centered, scaled uniformly, and clipped to a logical 450 × 800 canvas. This preserves its proportions when the window is resized.

Customize the effect

Try changing one setting at a time:

Setting Effect
SPACING Distance between lines; changes the scale of the moiré pattern.
3.5f stroke width Changes how much each layer covers the background.
10 in the angle calculation Average angle between layers.
7 in the angle calculation Amount of angular variation.
CYCLE Duration of one back-and-forth rotation.
Layer colors and alpha values Change the contrast and overlap colors.

Start by increasing SPACING from 11 to 15. The fine lines and the broad pattern will both become more widely spaced.

The complete source code above is free to copy and run. Explore the SwingLoops repository for more Java animation examples.