How do I read a text file using Files.readString() in Java?

You can use Files.readString() to read an entire text file into a single string. It preserves the file’s line separators, so the result can contain multiple lines.

In this example, you will read a UTF-8 text file and display its contents.

Source code

Save the following code as ReadStringExample.java:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class ReadStringExample {
    void main() {
        Path path = Path.of("message.txt");

        try {
            String content = Files.readString(path, StandardCharsets.UTF_8);

            IO.print(content);
        } catch (IOException exception) {
            System.err.println("Could not read the file: " + exception.getMessage());
        }
    }
}

Prepare the text file

Create a file named message.txt in the directory from which you will run the program. Save it using UTF-8 encoding with the following contents:

Hello, Java!
Learning Java one snippet at a time.

Explanation

The example creates a Path representing the file location:

Path path = Path.of("message.txt");

This is a relative path. Java resolves it against the program’s current working directory, which may differ from the directory containing the source file.

Reading the contents

The following statement reads the entire file:

String content = Files.readString(path, StandardCharsets.UTF_8);

The first argument identifies the file. The second specifies how its bytes are decoded into characters.

Using StandardCharsets.UTF_8 makes the expected encoding explicit. The overload Files.readString(path) also uses UTF-8.

The method returns one string containing all the text, including any line separators in the file.

Displaying the text

The program prints the contents using:

IO.print(content);

IO.print() does not append a line separator. This lets the program display the text without adding an extra newline beyond those already in the file.

Handling read failures

Files.readString() can throw an IOException, for example when the file is missing or cannot be read.

The catch block handles that failure:

catch (IOException exception) {
    System.err.println("Could not read the file: " + exception.getMessage());
}

The error message goes to standard error, while the file contents go to standard output.

You do not need to close a reader yourself. Files.readString() manages the file resource and closes it when reading finishes or an error occurs.

Run the example

With message.txt in your current directory, compile and run the program:

javac ReadStringExample.java
java ReadStringExample

Output

Hello, Java!
Learning Java one snippet at a time.

Use Files.readString() for files that comfortably fit in memory. For large files, process the contents incrementally with a buffered reader or Files.lines() instead.

How Do I Create My First Spring MVC Application?

In the previous tutorial, we introduced Spring MVC and learned how the DispatcherServlet handles incoming HTTP requests.

In this tutorial, we will create our first working Spring MVC application using Java 25, Spring Framework 7.1.0, and Maven.

We will configure Spring MVC using Java classes instead of XML and deploy the application to Apache Tomcat 11.

We will not use Spring Boot in this example. This allows us to understand the basic components required to run a Spring MVC application.

1. Prerequisites

Before starting, make sure you have installed:

  • Java Development Kit (JDK) 25
  • Apache Maven 3.9 or later
  • Apache Tomcat 11
  • An IDE such as IntelliJ IDEA, Eclipse, or Visual Studio Code
  • Basic knowledge of Java classes and annotations

We will use the following technologies:

Technology Version Purpose
Java 25 Programming language
Spring Framework 7.1.0 Spring MVC framework
Jakarta Servlet API 6.1.0 Servlet interfaces
Apache Tomcat 11.x Web application server
Maven 3.9+ Build and dependency management

Tomcat 11 supports Jakarta Servlet 6.1, which is compatible with our application.

2. Create a Maven Project

Create a Maven project named spring-mvc-hello.

Use the following project information:

Group ID    : org.kodejava
Artifact ID : spring-mvc-hello
Version     : 1.0.0
Packaging   : war

Our application will have the following directory structure:

spring-mvc-hello/
├── pom.xml
└── src/
    └── main/
        ├── java/
        │   └── org/
        │       └── kodejava/
        │           └── springmvc/
        │               ├── config/
        │               │   ├── WebConfig.java
        │               │   └── WebAppInitializer.java
        │               └── controller/
        │                   └── HelloController.java
        └── webapp/
            └── WEB-INF/
                └── views/
                    └── hello.jsp

We will create each file step by step.

3. Configure Maven

Open the pom.xml file and configure the project dependencies.

We need spring-webmvc to provide the Spring MVC functionality and jakarta.servlet-api for the servlet interfaces.

The servlet API uses the provided scope because Tomcat already supplies it when the application is deployed.

Here is the complete pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<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>spring-mvc-hello</artifactId>
    <version>1.0.0</version>
    <packaging>war</packaging>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>6.1.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>spring-mvc-hello</finalName>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.14.1</version>
                <configuration>
                    <release>25</release>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.5.0</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

The war packaging type tells Maven to create a Web Application Archive that can be deployed to Tomcat.

The failOnMissingWebXml configuration allows us to build the application without a traditional web.xml deployment descriptor.

4. Create the Spring MVC Configuration

Next, create the WebConfig.java class in the config package.

package org.kodejava.springmvc.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import org.springframework.context.annotation.Bean;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "org.kodejava.springmvc.controller")
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver =
                new InternalResourceViewResolver();

        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");

        return resolver;
    }
}

Let’s understand the annotations and configuration.

@Configuration

The @Configuration annotation tells Spring that the class contains bean definitions and application configuration.

@EnableWebMvc

The @EnableWebMvc annotation enables Spring MVC configuration, including support for annotated controllers and request mappings.

@ComponentScan

The @ComponentScan annotation tells Spring where to find components such as classes annotated with @Controller.

In this example, Spring scans the org.kodejava.springmvc.controller package.

InternalResourceViewResolver

The InternalResourceViewResolver converts a logical view name into a JSP file path.

For example, when a controller returns:

return "hello";

Spring MVC resolves the view to:

/WEB-INF/views/hello.jsp

Placing JSP files under WEB-INF prevents users from accessing them directly through a browser. Instead, the pages are reached through Spring MVC controllers.

5. Register the DispatcherServlet

The DispatcherServlet is the central component of Spring MVC.

It receives HTTP requests and delegates them to the appropriate controller.

In older applications, developers commonly registered the DispatcherServlet using a web.xml file.

Modern Spring MVC applications can use Java configuration instead.

Create WebAppInitializer.java:

package org.kodejava.springmvc.config;

import org.springframework.web.servlet.support
        .AbstractAnnotationConfigDispatcherServletInitializer;

public class WebAppInitializer
        extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { WebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

The AbstractAnnotationConfigDispatcherServletInitializer helps initialize Spring MVC when the servlet container starts the application.

We override three methods:

getRootConfigClasses()

Returns the configuration classes for the root application context. We return null because this simple application does not need a separate root context.

getServletConfigClasses()

Returns the Spring MVC configuration classes. In our application, this is WebConfig.class.

getServletMappings()

Defines which URL patterns are handled by the DispatcherServlet.

Using / allows the servlet to handle application requests while retaining the servlet container’s normal handling for JSP resources.

6. Create Your First Controller

Now we can create a controller that handles an HTTP request.

Create HelloController.java in the controller package.

package org.kodejava.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {

    @GetMapping("/hello")
    public String hello(Model model) {
        model.addAttribute(
                "message",
                "Hello, Spring MVC!"
        );

        return "hello";
    }
}

Let’s examine the controller.

@Controller

The @Controller annotation identifies the class as a Spring MVC controller.

Spring detects the class during component scanning and registers it as a bean.

@GetMapping

The @GetMapping("/hello") annotation maps HTTP GET requests to the hello() method.

When a user visits /hello, Spring MVC invokes this method.

Model

The Model interface allows us to pass data from the controller to the view.

In this example:

model.addAttribute("message", "Hello, Spring MVC!");

We add a model attribute named message.

The JSP page can access this attribute using Expression Language (EL).

Returning the View Name

The statement:

return "hello";

does not return the text hello to the browser.

Because the class uses @Controller, the returned string is interpreted as a logical view name.

Spring MVC uses our view resolver to locate hello.jsp.

7. Create the JSP View

Create the following file:

src/main/webapp/WEB-INF/views/hello.jsp

Add this HTML and JSP content:

<%@ page contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">

    <title>My First Spring MVC Application</title>

    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f5f7fa;
            margin: 0;
            padding: 40px;
        }

        .container {
            max-width: 600px;
            margin: 60px auto;
            padding: 32px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
            text-align: center;
        }

        h1 {
            color: #2563eb;
        }

        p {
            color: #475569;
        }
    </style>
</head>
<body>
    <main class="container">
        <h1>${message}</h1>
        <p>My first Spring MVC application is running!</p>
    </main>
</body>
</html>

The expression:

${message}

reads the message attribute added by the controller.

The JSP engine evaluates this expression and inserts the value into the generated HTML.

For this example, the message is a fixed string defined by the application. In applications that display user-provided content, use output escaping to prevent cross-site scripting vulnerabilities.

8. Build the Application

Open a terminal in the project directory.

Run:

mvn clean package

Maven will compile the Java classes, resolve dependencies, and package the application into a WAR file.

If the build succeeds, you should see a message similar to:

[INFO] BUILD SUCCESS

The generated file is located at:

target/spring-mvc-hello.war

9. Deploy the Application to Tomcat

Download and extract Apache Tomcat 11 if you have not installed it already.

Copy the generated WAR file into Tomcat’s webapps directory.

On Linux or macOS, for example:

cp target/spring-mvc-hello.war \
   /path/to/tomcat/webapps/

On Windows PowerShell:

Copy-Item `
    target/spring-mvc-hello.war `
    C:\apache-tomcat-11\webapps\

Adjust the Tomcat directory to match your installation.

Start Tomcat using its startup script.

Linux or macOS:

/path/to/tomcat/bin/startup.sh

Windows:

C:\apache-tomcat-11\bin\startup.bat

If Tomcat is already running with automatic deployment enabled, it may deploy the WAR without a restart.

10. Test the Application

Open your browser and visit:

http://localhost:8080/spring-mvc-hello/hello

You should see a page displaying:

Hello, Spring MVC!

My first Spring MVC application is running!

The page will use the CSS styles defined in our JSP file.

You can also inspect the HTTP response using curl:

curl -i http://localhost:8080/spring-mvc-hello/hello

A successful request returns an HTTP 200 response with HTML content.

11. Understanding the Request Flow

Let’s review what happens when the browser requests our page.

Browser
   |
   | GET /spring-mvc-hello/hello
   v
Apache Tomcat
   |
   v
DispatcherServlet
   |
   v
HelloController
   |
   | model.addAttribute(...)
   | return "hello"
   v
View Resolver
   |
   v
/WEB-INF/views/hello.jsp
   |
   v
HTML Response
   |
   v
Browser

The request passes through these steps:

  1. The browser sends an HTTP GET request.
  2. Tomcat receives the request and forwards it to the DispatcherServlet.
  3. Spring MVC finds the controller method mapped to /hello.
  4. The controller adds the greeting message to the model.
  5. The controller returns the logical view name hello.
  6. The view resolver locates the JSP page.
  7. The JSP engine renders the page into HTML.
  8. Tomcat sends the generated HTML back to the browser.

This is the basic request-processing flow of a traditional Spring MVC application.

12. Common Problems

HTTP 404 Not Found

If the browser displays a 404 error, check the following:

  • The WAR file was deployed successfully.
  • The application context path is /spring-mvc-hello.
  • The controller uses @GetMapping("/hello").
  • The application started without deployment errors.

HTTP 500 Internal Server Error

A 500 error may indicate a problem with application configuration or JSP rendering.

Check the Tomcat logs in the logs directory for the underlying exception.

JSP File Cannot Be Found

Verify that your JSP file is located at:

src/main/webapp/WEB-INF/views/hello.jsp

Also verify that the prefix and suffix in WebConfig match the file location.

Java Version Errors

Make sure Maven and Tomcat are running with compatible Java versions.

Run:

java -version
mvn -version

The project is compiled for Java 25, so Tomcat must also run on Java 25 or a compatible newer Java runtime.

13. Summary

In this tutorial, we created our first Spring MVC application using Java configuration.

We learned how to:

  • Create a Maven-based Spring MVC project.
  • Configure Spring MVC with @EnableWebMvc.
  • Register the DispatcherServlet without web.xml.
  • Create a controller using @Controller and @GetMapping.
  • Pass data from a controller to a JSP view.
  • Configure an InternalResourceViewResolver.
  • Package the application as a WAR file.
  • Deploy and run the application on Apache Tomcat.

We now have a working Spring MVC application and understand how its main components work together.

In the next tutorial, How Does the DispatcherServlet Work in Spring MVC?, we will explore the internal request-processing mechanism, including handler mappings, handler adapters, and view resolution.

14. Maven Artifacts

The following Maven artifacts are required for this tutorial.

Spring Web MVC

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>7.1.0</version>
</dependency>

Maven artifact: org.springframework:spring-webmvc:7.1.0

Jakarta Servlet API

<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.1.0</version>
    <scope>provided</scope>
</dependency>

Maven artifact: jakarta.servlet:jakarta.servlet-api:6.1.0

Maven Compiler Plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.14.1</version>
</plugin>

Maven WAR Plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>3.5.0</version>
</plugin>

Spring MVC automatically brings in several Spring dependencies through Maven’s transitive dependency management, so we do not need to declare each one manually.

References

How do I implement the Builder pattern in Java?

Suppose a reporting application produces a plain text summary for an email and an HTML fragment for a dashboard. Both reports contain a title and a sequence of items. We want to reuse the steps that assemble the report while allowing each output format to control how those steps are represented.

Builder is a Gang of Four creational pattern that separates the construction steps of a complex object from its representation. A director coordinates those steps through a builder interface. Concrete builders assemble the results in their own formats. The GoF describe this intent in their pattern catalog. Design Patterns by Gamma, Helm, Johnson, and Vlissides

This example uses a small report to make the construction sequence visible. The same approach can support richer reports with sections, tables, and summaries.

A complete example

Save the code as BuilderExample.java. It uses only standard Java classes and supports Java 8 or later.

package org.kodejava.pattern.builder;

import java.util.Arrays;
import java.util.List;

public class BuilderExample {
    interface ReportBuilder {
        void start(String title);
        void addItem(String item);
        void finish();
        String getResult();
    }

    static final class PlainTextReportBuilder implements ReportBuilder {
        private final StringBuilder content = new StringBuilder();

        @Override
        public void start(String title) {
            content.setLength(0);
            content.append(title).append("\n");
        }

        @Override
        public void addItem(String item) {
            content.append("- ").append(item).append("\n");
        }

        @Override
        public void finish() {
            // Plain text needs no closing markup.
        }

        @Override
        public String getResult() {
            return content.toString();
        }
    }

    static final class HtmlReportBuilder implements ReportBuilder {
        private final StringBuilder content = new StringBuilder();

        @Override
        public void start(String title) {
            content.setLength(0);
            content.append("<h1>").append(escape(title)).append("</h1><ul>");
        }

        @Override
        public void addItem(String item) {
            content.append("<li>").append(escape(item)).append("</li>");
        }

        @Override
        public void finish() {
            content.append("</ul>");
        }

        @Override
        public String getResult() {
            return content.toString();
        }

        private String escape(String value) {
            return value.replace("&", "&")
                    .replace("<", "<")
                    .replace(">", ">");
        }
    }

    static final class ReportDirector {
        void construct(ReportBuilder builder, String title, List<String> items) {
            builder.start(title);
            for (String item : items) {
                builder.addItem(item);
            }
            builder.finish();
        }
    }

    public static void main(String[] args) {
        ReportDirector director = new ReportDirector();
        List<String> items = Arrays.asList("Orders: 12", "Returns & exchanges: 2");
        ReportBuilder plainText = new PlainTextReportBuilder();
        director.construct(plainText, "Weekly report", items);
        System.out.print(plainText.getResult());

        ReportBuilder html = new HtmlReportBuilder();
        director.construct(html, "Weekly report", items);
        System.out.println(html.getResult());
    }
}

Compile and run it from the directory containing the source.

javac -d out BuilderExample.java
java -cp out org.kodejava.pattern.builder.BuilderExample

The output contains the plain text report followed by the HTML fragment.

Weekly report
- Orders: 12
- Returns & exchanges: 2
<h1>Weekly report</h1><ul><li>Orders: 12</li><li>Returns & exchanges: 2</li></ul>

The HTML builder escapes ampersands and angle brackets in text content. The sample’s ampersand becomes &amp;, keeping it as text inside the list item.

How the construction works

GoF role Example Responsibility
Builder ReportBuilder Declares the report construction steps.
Concrete builders PlainTextReportBuilder, HtmlReportBuilder Assemble the report in each format.
Director ReportDirector Calls the steps in the required order.
Products Plain text and HTML strings Hold the completed representations.
Client main() Chooses each builder and retrieves its result.

The director starts the report, adds each item, then finishes it. It uses the same sequence for both builders. The plain text builder adds line breaks and bullet markers. The HTML builder creates heading and list elements.

Although both results have Java type String, they represent different output formats. Each concrete builder owns the rules for assembling its representation.

The client calls getResult() after construction completes. Calling it earlier would return the content assembled so far. The director supplies the ordering contract for this example.

Each builder’s start() method clears its buffer, so a later construction using that builder replaces the previous report. Previously returned strings retain their contents. The mutable builders should be confined to one construction at a time.

Adding another representation

A new builder can implement the same operations for another report format. The client passes it to the director and retrieves the result after construction. A new construction operation, such as adding a table, requires updating the builder interface, implementations, and director where appropriate.

In Java APIs, you may also encounter fluent builders with chained configuration methods and a final build() call. This example makes the GoF construction process explicit through a director and interchangeable representations. Method chaining is an optional API choice.

When should I use Builder?

Builder fits a construction process with multiple steps that can be reused across different representations. Examples include document generation and assembling complex object structures from parsed input.

The additional interface and classes have a maintenance cost. For a short report with one fixed output format, a single formatting method can be sufficient. As formats and construction rules grow, builders give each representation a dedicated place to manage its assembly.

This continues the creational series after Factory Method and Abstract Factory. The series began with the existing Singleton article. Singleton pattern

Next, we will cover Prototype and create new objects by copying an existing instance.

How do I create a game window using Java Swing?

In the previous tutorial, How do I get started with 2D game programming in Java?, we created our first game window and drew a simple rectangle using Java Swing.

Our first example placed everything inside a single Java class. This approach is useful when learning the basics, but as we add more features, our game will become harder to maintain.

In this tutorial, we will improve the structure of our project by separating the game window from the drawing area.

By the end of this tutorial, you will learn how to:

  • Create a game window using JFrame.
  • Create a drawing area using JPanel.
  • Separate the game window and rendering responsibilities.
  • Configure the window size, title, and close operation.
  • Draw a simple player object using Graphics2D.
  • Start a Swing application using the Event Dispatch Thread.

We will continue using Java 25, Java Swing, and Apache Maven.

1. Understanding the game window

Before writing the code, let’s understand the two main components we will use.

JFrame — The game window

JFrame represents the main window of our desktop application.

It provides a title bar, borders, and window controls such as minimize, maximize, and close.

In our game, the frame acts as a container for the drawing area.

JPanel — The drawing area

JPanel is a Swing component that can be used to organize other components or display custom graphics.

We will extend JPanel and override its paintComponent() method to draw our game objects.

Our application will have three classes:

Class Responsibility
Game Starts the application
GameWindow Creates and configures the main window
GamePanel Draws the game content

This separation makes our code easier to understand and extend.

Later, we can add classes for player movement, keyboard input, game objects, and collision detection without putting everything inside a single class.

2. Creating the Maven project

Create a Maven project named java-2d-game.

We will organize the project using the following structure:

java-2d-game/
├── pom.xml
└── src/
    └── main/
        └── java/
            └── org/
                └── kodejava/
                    └── game/
                        ├── Game.java
                        ├── GameWindow.java
                        └── GamePanel.java

All three classes belong to the org.kodejava.game package.

If you are continuing from Week 01, replace the previous Game.java implementation and add the two new classes.

3. Creating the GamePanel class

Let’s start with the drawing area.

Create a file named GamePanel.java:

package org.kodejava.game;

import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

public class GamePanel extends JPanel {

    public static final int GAME_WIDTH = 800;
    public static final int GAME_HEIGHT = 600;

    public GamePanel() {
        setPreferredSize(new Dimension(
                GAME_WIDTH, GAME_HEIGHT));

        setBackground(new Color(15, 23, 42));
        setDoubleBuffered(true);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g.create();

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

            drawWelcomeMessage(g2d);
            drawPlayer(g2d);
        } finally {
            g2d.dispose();
        }
    }

    private void drawWelcomeMessage(Graphics2D g2d) {
        g2d.setColor(Color.WHITE);
        g2d.setFont(new Font(
                Font.SANS_SERIF, Font.BOLD, 24));

        String message = "Welcome to Java 2D Game!";

        int textWidth = g2d.getFontMetrics()
                .stringWidth(message);

        int x = (GAME_WIDTH - textWidth) / 2;
        int y = 150;

        g2d.drawString(message, x, y);
    }

    private void drawPlayer(Graphics2D g2d) {
        int playerSize = 50;

        int x = (GAME_WIDTH - playerSize) / 2;
        int y = (GAME_HEIGHT - playerSize) / 2;

        g2d.setColor(new Color(96, 165, 250));
        g2d.fillRect(x, y, playerSize, playerSize);
    }
}

Understanding setPreferredSize()

The following code defines the preferred size of our game panel:

setPreferredSize(new Dimension(
        GAME_WIDTH, GAME_HEIGHT));

We use an 800 × 600 pixel drawing area.

Notice that this defines the size of the game panel, not necessarily the entire desktop window.

The outer window also includes decorations such as the title bar and borders.

Understanding paintComponent()

The paintComponent() method is responsible for drawing the content of our panel.

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g.create();

    try {
        drawWelcomeMessage(g2d);
        drawPlayer(g2d);
    } finally {
        g2d.dispose();
    }
}

The Graphics object represents the drawing context supplied by Swing.

We create a separate graphics context using g.create() so that changes to rendering settings do not affect the original context.

Calling dispose() releases the resources associated with our copy.

Important: We must not call dispose() on the original Graphics object provided by Swing.

Why do we call super.paintComponent()?

The following statement should usually be the first operation in our overridden painting method:

super.paintComponent(g);

It allows Swing to perform the standard painting behavior for the component.

Since our panel is opaque and has a background color, this also allows Swing to clear the drawing area before we render our objects.

What is double buffering?

Double buffering is a technique that helps reduce flickering while drawing graphics.

Instead of exposing partially drawn frames directly to the screen, the drawing operations can be performed using an offscreen buffer.

The completed image is then displayed.

In our example, we call:

setDoubleBuffered(true);

Swing already uses double buffering for normal painting in common configurations, so this call makes our intention explicit.

We do not need to create a separate image buffer manually.

Later in the series, we will learn more about smooth animation and efficient rendering.

4. Creating the GameWindow class

Now we need a class that creates and configures the main window.

Create GameWindow.java:

package org.kodejava.game;

import javax.swing.JFrame;

public class GameWindow extends JFrame {

    public GameWindow() {
        setTitle("KodeJava 2D Game");

        setDefaultCloseOperation(
                JFrame.EXIT_ON_CLOSE);

        setContentPane(new GamePanel());

        pack();
        setLocationRelativeTo(null);
        setResizable(false);
        setVisible(true);
    }
}

This class extends JFrame, so it inherits the functionality of a Swing window.

Let’s examine its configuration.

Setting the window title

setTitle("KodeJava 2D Game");

This determines the text displayed in the window’s title bar.

Configuring the close operation

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

This tells Swing to exit the application when the user closes the window.

For our simple standalone game, this behavior is appropriate.

Adding the GamePanel

setContentPane(new GamePanel());

This places our custom game panel inside the frame as its content pane.

The GameWindow class does not need to know how the panel draws its contents.

Its responsibility is to manage the window.

Using pack()

pack();

The pack() method sizes the frame according to the preferred sizes of its contained components.

Because our GamePanel requests an 800 × 600 drawing area, pack() calculates a suitable frame size that also accounts for the window’s decorations.

This is generally better than using setSize(800, 600) when we want the actual game area to have a specific size.

Centering the game window

setLocationRelativeTo(null);

This positions the window in the center of the screen.

Preventing window resizing

setResizable(false);

For now, we will use a fixed-size window.

This makes it easier to understand coordinates and object positions.

We can introduce resizable windows and scaling after learning more about rendering.

5. Creating the Game class

Finally, create the application’s entry point.

Create Game.java:

package org.kodejava.game;

import javax.swing.SwingUtilities;

public class Game {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(GameWindow::new);
    }
}

This is now a very small class.

Its only responsibility is to start our application.

Why use SwingUtilities.invokeLater()?

Swing applications use the Event Dispatch Thread (EDT) to process events and interact with GUI components.

The following code schedules creation of our window on the EDT:

SwingUtilities.invokeLater(GameWindow::new);

This is equivalent to:

SwingUtilities.invokeLater(() -> {
    new GameWindow();
});

A constructor reference is simply a more concise way to express the same operation.

Creating and updating Swing components on the EDT helps avoid threading problems.

When we introduce a game loop, we will also learn why long-running calculations should not block this thread.

6. Running the game

We now have three Java classes:

  • Game.java
  • GameWindow.java
  • GamePanel.java

Compile the project:

mvn clean compile

Then run the application from your IDE.

You can also execute it from the command line:

java -cp target/classes org.kodejava.game.Game

If everything works correctly, a window titled KodeJava 2D Game will appear.

Game Window

Inside the window, you should see:

  • A dark background.
  • A white welcome message.
  • A blue square positioned in the center of the drawing area.

The blue square represents our player.

It does not move yet, but our project now has a better structure for future development.

7. Understanding the rendering coordinates

Java 2D uses a coordinate system where the origin (0, 0) is located at the upper-left corner of the component.

The horizontal coordinate increases toward the right, and the vertical coordinate increases downward.

For example:

g2d.fillRect(100, 150, 50, 50);

This draws a rectangle with its top-left corner at (100, 150).

Its width and height are both 50 pixels.

In our drawPlayer() method, we use a simple calculation to position the player in the center:

int playerSize = 50;

int x = (GAME_WIDTH - playerSize) / 2;
int y = (GAME_HEIGHT - playerSize) / 2;

For an 800 × 600 drawing area and a 50 × 50 player, the calculated position is:

x = (800 - 50) / 2 = 375
y = (600 - 50) / 2 = 275

This places the rectangle’s top-left corner at (375, 275).

Its center is therefore at (400, 300), which is the center of our game area.

We will explore coordinates in more detail in Week 04.

8. Why separate GameWindow and GamePanel?

You might wonder why we need several classes when the previous example worked with only one.

The main reason is separation of responsibilities.

GameWindow handles the desktop window, while GamePanel handles the drawing area.

This separation becomes more valuable as we develop larger games.

For example, later we can extend our project with additional classes:

org.kodejava.game
├── Game.java
├── GameWindow.java
├── GamePanel.java
├── Player.java
├── Enemy.java
└── GameLoop.java

Each class will have a specific responsibility.

This approach makes our code easier to read, test, maintain, and reuse.

For a simple example, three classes may seem unnecessary. However, we are preparing a foundation for projects that will eventually include movement, animation, collision detection, and game logic.

9. Try it yourself

Before moving to the next tutorial, try these exercises.

Exercise 1 — Change the game resolution

Modify the dimensions in GamePanel:

public static final int GAME_WIDTH = 1024;
public static final int GAME_HEIGHT = 768;

Run the application again.

Notice how pack() automatically adjusts the window to accommodate the new preferred size.

Exercise 2 — Change the background color

Replace:

setBackground(new Color(15, 23, 42));

with:

setBackground(Color.DARK_GRAY);

Exercise 3 — Draw another object

Add the following code inside drawPlayer():

g2d.setColor(Color.YELLOW);
g2d.fillOval(100, 100, 40, 40);

Now the game displays both a square and a circle.

Exercise 4 — Allow window resizing

Change:

setResizable(false);

to:

setResizable(true);

Try resizing the window.

Notice that our player position is still calculated using the fixed values GAME_WIDTH and GAME_HEIGHT.

This means the player will not automatically remain centered when the window becomes larger.

As an additional challenge, try using getWidth() and getHeight() from GamePanel when calculating the player position.

10. Summary

In this tutorial, we improved the structure of our Java 2D game project.

We learned how to:

  • Create a main game window using JFrame.
  • Create a custom drawing panel using JPanel.
  • Separate window management from rendering.
  • Configure window dimensions and positioning.
  • Draw text and objects using Graphics2D.
  • Start Swing components on the Event Dispatch Thread.
  • Understand the basic coordinate system used for drawing.

Our game is still simple, but we now have a foundation that can grow into a complete 2D game.

In the next tutorial, How do I draw 2D shapes using Graphics2D?, we will learn how to draw lines, rectangles, circles, and other shapes, as well as how to use colors and rendering settings.

Maven Dependencies

Java Swing and Java 2D are included in the standard Java Development Kit as part of the java.desktop module.

We do not need any external libraries for this tutorial.

Here is the complete pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<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>java-2d-game</artifactId>
    <version>1.0-SNAPSHOT</version>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.14.1</version>
            </plugin>
        </plugins>
    </build>
</project>

Required Maven dependencies: None.

Build plugin: org.apache.maven.plugins:maven-compiler-plugin:3.14.1

References

How do I convert a list of strings to uppercase using a stream in Java?

You can use the Stream API’s map() method to transform each string in a list. Call toUpperCase() inside the mapping function, then collect the results with toList().

In this example, you will convert programming language names to uppercase without changing the original list.

Source code

Save the following code as UppercaseListExample.java:

import java.util.List;
import java.util.Locale;

public class UppercaseListExample {
    void main() {
        List<String> languages = List.of(
                "Java", "Python", "Kotlin");

        List<String> uppercaseLanguages = languages.stream()
                .map(language -> language.toUpperCase(Locale.ROOT))
                .toList();

        IO.println("Original list: " + languages);
        IO.println("Uppercase list: " + uppercaseLanguages);
    }
}

Explanation

The original list contains three strings with mixed capitalization:

List<String> languages = List.of(
        "Java", "Python", "Kotlin");

The following pipeline transforms each element and collects the results:

List<String> uppercaseLanguages = languages.stream()
        .map(language -> language.toUpperCase(Locale.ROOT))
        .toList();

Each step has a purpose:

Step Purpose
stream() Creates a sequential stream of the list’s elements
map(...) Converts each string to uppercase
toList() Collects the converted strings into an unmodifiable list

Transforming each element

The map() method applies a function to each element:

language -> language.toUpperCase(Locale.ROOT)

For example, "Java" becomes "JAVA".

Unlike filter(), which selects matching elements, map() transforms them. This pipeline produces one result for each input element.

Choosing a locale

Uppercase conversion can depend on language rules. Calling toUpperCase() without an argument uses the system’s default locale.

This example passes Locale.ROOT explicitly:

language.toUpperCase(Locale.ROOT)

It uses language-neutral casing rules, making the conversion independent of the system’s default locale. For text intended for a specific language, use the appropriate locale instead.

Keeping the original values

Strings are immutable. Calling toUpperCase() returns an uppercase result without modifying the original string.

The stream pipeline also leaves the original list unchanged. The result list preserves the original element order.

The list returned by toList() is unmodifiable. Calling add(), remove(), or set() on it would throw an UnsupportedOperationException.

Run the example

Compile and run the file:

javac UppercaseListExample.java
java UppercaseListExample

Output

Original list: [Java, Python, Kotlin]
Uppercase list: [JAVA, PYTHON, KOTLIN]

Use map() when you want to transform every element, such as converting text, extracting an object’s field, or calculating a new value.