How do I split a string into words in Java?

You can use the split() method to divide a string into smaller parts. The method accepts a regular expression that defines where to split and returns an array of strings.

In this example, you will split a sentence into words using whitespace as the separator.

Source code

Save the following code as SplitStringExample.java:

public class SplitStringExample {
    void main() {
        String text = "  Learn Java   one snippet\tat a time.  ";

        if (text.isBlank()) {
            IO.println("The text contains no words.");
            return;
        }

        String[] words = text.strip().split("\\p{javaWhitespace}+");

        for (String word : words) {
            IO.println(word);
        }

        IO.println("Total words: " + words.length);
    }
}

Explanation

The input contains spaces at both ends, multiple spaces between some words, and a tab character:

String text = "  Learn Java   one snippet\tat a time.  ";

The escape sequence \t represents a tab.

Checking for blank text

Before splitting, the program checks whether the text is empty or contains only whitespace:

if (text.isBlank()) {
    IO.println("The text contains no words.");
    return;
}

This avoids treating an empty string as a word. The return statement ends the method when there is no text to process.

Removing surrounding whitespace

The strip() method removes leading and trailing whitespace:

text.strip()

It returns a string without changing the original string, because strings are immutable.

Splitting on whitespace

The following statement splits the cleaned text:

String[] words = text.strip().split("\\p{javaWhitespace}+");

The regular expression has two parts:

Part Meaning
\p{javaWhitespace} Matches whitespace recognized by Character.isWhitespace()
+ Matches one or more consecutive whitespace characters

The backslash is written twice in the Java string literal so the regular expression receives a single backslash.

Using + treats consecutive spaces or tabs as one separator. This prevents empty elements between words when several whitespace characters appear together.

Reading the results

The enhanced for loop prints each element:

for (String word : words) {
    IO.println(word);
}

The array’s length field gives the number of resulting words.

Run the example

Compile and run the file:

javac SplitStringExample.java
java SplitStringExample

Output

Learn
Java
one
snippet
at
a
time.
Total words: 7

This example treats each whitespace-separated token as a word. Punctuation remains attached, so the last token is "time.". For language-aware word boundaries, use a text-processing tool such as BreakIterator.

How do I get started with 2D game programming in Java?

Game programming is a fun way to learn Java because it combines programming concepts with visual results. Instead of writing programs that only print text to the console, we can create characters, draw objects, and eventually build interactive games.

In this tutorial, we will take our first step into 2D game programming using Java Swing. We will create a simple game window and draw a player represented by a blue square.

This is the first article in our 2D Game Programming with Java Swing series, where we will learn to build games from scratch without relying on an external game engine.

What is 2D game programming?

A 2D game is a game where objects are positioned in a two-dimensional space using horizontal and vertical coordinates.

Some familiar examples include Pong, Snake, Breakout, and traditional platform games.

Most 2D games share several important concepts:

  • Game window: The area where the game is displayed.
  • Game objects: Players, enemies, obstacles, and other elements.
  • Rendering: Drawing game objects on the screen.
  • Input handling: Responding to keyboard and mouse input.
  • Game loop: Continuously updating and displaying the game.
  • Collision detection: Detecting when objects touch or overlap.

We will explore these concepts one at a time throughout the series.

Why use Java Swing?

Java Swing is a GUI toolkit included in the Java Development Kit (JDK). Although it was primarily designed for desktop applications, we can also use it to build simple 2D games.

Swing provides several useful classes:

Class Purpose
JFrame Creates the main game window
JPanel Provides an area for drawing game objects
Graphics Offers basic drawing operations
Graphics2D Provides more advanced 2D drawing capabilities
Timer Can schedule periodic updates for simple games

One advantage of using Swing is that we do not need to install an additional game engine.

By building games directly with Swing and Java 2D, we can better understand the fundamental techniques used in game development.

What do we need?

Before getting started, make sure you have:

  • Java Development Kit (JDK) 25
  • Apache Maven
  • A Java IDE such as IntelliJ IDEA, Eclipse, or NetBeans

We will use Java 25, an LTS release, for this series.

To verify your Java installation, open a terminal and run:

java -version

Then check your Maven installation:

mvn -version

Creating our first game project

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

Our initial project structure will look like this:

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

We will start with a single Java class to keep the example easy to understand.

As our game becomes more complex, we will introduce additional classes to organize the code.

Creating the game window

Let’s create a Java class named Game.java.

package org.kodejava.game;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;

public class Game extends JPanel {

    private static final int WIDTH = 800;
    private static final int HEIGHT = 600;

    public Game() {
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        setBackground(Color.BLACK);
    }

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

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

        try {
            g2d.setColor(Color.BLUE);
            g2d.fillRect(100, 100, 50, 50);
        } finally {
            g2d.dispose();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("My First Java 2D Game");

            frame.setDefaultCloseOperation(
                    JFrame.EXIT_ON_CLOSE);

            frame.add(new Game());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setResizable(false);
            frame.setVisible(true);
        });
    }
}

When we run this program, a window will appear with a black background and a blue square.

The square represents our first game object. It does not move yet, but it provides a starting point for the next tutorials.

Game Window

Game Window

Understanding the code

Let’s examine the important parts of our program.

Extending JPanel

public class Game extends JPanel {

By extending JPanel, our class becomes a Swing component that can display custom graphics.

We can override its painting method to draw our game objects.

Setting the game area

setPreferredSize(new Dimension(800, 600));
setBackground(Color.BLACK);

Here, we define a preferred game area of 800 pixels wide and 600 pixels high.

We also set the background color to black.

Drawing the player

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

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

    try {
        g2d.setColor(Color.BLUE);
        g2d.fillRect(100, 100, 50, 50);
    } finally {
        g2d.dispose();
    }
}

The paintComponent() method is called by Swing when the component needs to be painted.

We call super.paintComponent(g) first so that Swing can perform its standard component painting.

Next, we create a copy of the graphics context and use Graphics2D to draw a rectangle.

The fillRect() method accepts four parameters:

fillRect(x, y, width, height);

In our example:

  • x = 100: The horizontal position.
  • y = 100: The vertical position.
  • width = 50: The rectangle width.
  • height = 50: The rectangle height.

The rectangle is drawn at position (100, 100) and has a size of 50 × 50 pixels.

Finally, we dispose of the copied graphics context to release its associated resources.

Creating the main window

JFrame frame = new JFrame("My First Java 2D Game");

The JFrame class creates the main desktop window.

We then add our game panel:

frame.add(new Game());

The pack() method adjusts the window size based on the preferred size of its contents.

We use setLocationRelativeTo(null) to center the window on the screen.

Understanding SwingUtilities.invokeLater()

SwingUtilities.invokeLater(() -> {
    // Create and display the game window
});

Swing uses a special thread called the Event Dispatch Thread (EDT) to process GUI events and update components.

Using SwingUtilities.invokeLater() ensures that our Swing interface is created on this thread.

This is important because most Swing components are not thread-safe.

Later in this series, we will learn how to coordinate game updates with Swing rendering.

Running the program

First, compile the project using Maven:

mvn compile

Then run the main class from your IDE.

Alternatively, after compiling, you can run it from the project root using:

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

You should see an 800 × 600 game area with a blue square displayed near the upper-left corner.

Congratulations! You have created your first 2D game window in Java.

Although the square is not interactive yet, we already have two essential components of a game: a window and a rendering area.

Try it yourself

Before moving to the next tutorial, try making a few changes to the program.

Exercise 1: Change the player color

Replace:

g2d.setColor(Color.BLUE);

with:

g2d.setColor(Color.GREEN);

Exercise 2: Move the player

Modify the rectangle position:

g2d.fillRect(300, 200, 50, 50);

Observe how the square appears at a different location.

Exercise 3: Change the player size

Try drawing a larger rectangle:

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

These simple exercises introduce coordinates, colors, and object dimensions, which are fundamental concepts in 2D game programming.

Summary

In this tutorial, we learned how to create our first 2D game window using Java Swing.

We covered:

  • The basic concepts of 2D game programming.
  • Why Java Swing is useful for learning game development.
  • How to create a game window using JFrame.
  • How to create a drawing area using JPanel.
  • How to draw a rectangle using Graphics2D.
  • Why Swing applications use the Event Dispatch Thread.

In the next tutorial, How do I create a game window using Java Swing?, we will explore game window configuration in greater detail and separate our main window from the drawing panel.

Maven Dependencies

Java Swing and Java 2D are included in the standard JDK through the java.desktop module, so no external dependencies are required.

We only need to configure Maven to compile our project with Java 25.

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 artifacts: None for Swing or Java 2D.

The Maven Compiler Plugin is configured as a build plugin, not an application dependency.

Java API references:

How do I get started with Spring MVC?

Spring MVC is a web framework built on top of the Spring Framework. It helps developers create web applications and REST APIs using the Model-View-Controller (MVC) architectural pattern.

In this tutorial, we will introduce Spring MVC, explore its main components, and understand how an HTTP request is processed.

1. What is Spring MVC?

Spring MVC is part of the Spring Framework and provides a structured way to handle HTTP requests, process application logic, and generate responses.

It follows the Model-View-Controller pattern, which separates an application into three main responsibilities:

  • Model: Represents application data and business information.
  • View: Displays information to users, typically as HTML.
  • Controller: Receives HTTP requests and coordinates the application’s response.

This separation makes applications easier to develop, maintain, and test.

Spring MVC can also build REST APIs that return JSON instead of HTML.

2. How does Spring MVC work?

The central component of Spring MVC is the DispatcherServlet. It acts as a front controller that receives incoming HTTP requests and delegates them to the appropriate controller.

Spring MVC Request Flow Diagram

When a browser sends an HTTP request, Spring MVC performs the following steps:

  1. The DispatcherServlet receives the request.
  2. Spring MVC identifies the appropriate controller method.
  3. The controller processes the request, often calling application services.
  4. The controller returns data or a view name.
  5. Spring MVC generates an HTTP response.

For HTML pages, a view resolver can help locate the appropriate view template. For REST APIs, an HTTP message converter can serialize Java objects into JSON.

3. Creating a simple Spring MVC controller

Let’s look at a simple controller that returns a greeting.

package org.kodejava.springmvc;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, Spring MVC!";
    }
}

The example uses two important annotations:

  • @RestController tells Spring that the class handles web requests and writes return values directly to the HTTP response body.
  • @GetMapping("/hello") maps HTTP GET requests for /hello to the sayHello() method.

When the application is properly configured and running, accessing /hello returns:

Hello, Spring MVC!

This controller is only one part of a Spring MVC application. We still need to configure the application context and register the DispatcherServlet before it can handle requests.

We will implement these components in the next tutorial.

4. Spring MVC vs. Spring Boot

Spring MVC and Spring Boot are related, but they serve different purposes.

Spring MVC Spring Boot
Web application framework Application configuration and bootstrapping
Provides controllers and request mappings Provides auto-configuration
Can be configured manually Simplifies application setup
Supports HTML and REST APIs Can run Spring MVC with an embedded server

Spring Boot does not replace Spring MVC. Instead, Spring Boot can configure and run Spring MVC applications with less setup.

5. Summary

In this tutorial, we learned that Spring MVC is a web framework based on the MVC architectural pattern. We also introduced the DispatcherServlet, explored the request processing flow, and created a simple REST controller.

In the next tutorial, How do I create my first Spring MVC application?, we will build a complete application using Java configuration and Maven.

6. Maven Dependencies

This series uses Spring Framework 7.0.10, the latest stable 7.0 release verified for November 10, 2026. Spring Framework 7.1 is still in its release-candidate stage.

Add the following dependency to your Maven pom.xml:

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

The dependency provides Spring MVC’s core functionality. A runnable web application will additionally need a compatible Jakarta Servlet environment, which we will configure later in this series.

How do I compare two strings in Java?

Use the equals() method to check whether two strings contain the same text. Use equalsIgnoreCase() when capitalization should not affect the comparison.

In this example, you will compare strings with identical text and strings with different capitalization.

Source code

Save the following code as StringComparisonExample.java:

public class StringComparisonExample {
    void main() {
        String first = "Java";
        String second = new String("Java");
        String third = "java";

        IO.println("Same text: " + first.equals(second));
        IO.println("Same object: " + (first == second));
        IO.println("Same case-sensitive text: " + first.equals(third));
        IO.println("Same text ignoring case: "
                + first.equalsIgnoreCase(third));
    }
}

Explanation

The example creates three string variables:

String first = "Java";
String second = new String("Java");
String third = "java";

The first two strings contain identical text. The third starts with a lowercase letter.

The explicit new String("Java") creates a separate object to demonstrate the difference between comparing text and comparing references. In ordinary code, prefer a string literal when you do not need a separate object.

Comparing text with equals()

The equals() method compares the contents of strings:

first.equals(second)

This returns true because both strings contain "Java".

The comparison is case-sensitive:

first.equals(third)

This returns false because "Java" and "java" have different capitalization.

Comparing references with ==

For strings, the == operator checks whether two references point to the same object:

first == second

This returns false because second refers to a separately created string object, even though the text is identical.

String literals may share an object, so == can sometimes return true for strings containing the same text. Always use equals() when your intention is to compare their contents.

Ignoring capitalization

Use equalsIgnoreCase() when letter case should not affect the result:

first.equalsIgnoreCase(third)

This returns true for "Java" and "java".

Run the example

Compile and run the file:

javac StringComparisonExample.java
java StringComparisonExample

Output

Same text: true
Same object: false
Same case-sensitive text: false
Same text ignoring case: true

Handling null values

Calling equals() on a variable containing null throws a NullPointerException.

When comparing a variable with a known string literal, put the literal first:

"Java".equals(value)

This returns false if value is null.

If either of two variables may be null, use Objects.equals():

Objects.equals(firstValue, secondValue)

Import java.util.Objects to use this method. It returns true when both arguments are null, and otherwise compares their values safely.

How do I use a method reference in Java?

A method reference lets you use an existing method as the implementation of a functional interface. It can make a lambda expression shorter when the lambda only calls that method.

In this example, you will use a method reference to print each language in a list.

Source code

Save the following code as MethodReferenceExample.java:

import java.util.List;

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

        languages.forEach(IO::println);
    }
}

Explanation

The example creates a list containing three language names:

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

The forEach() method performs an action for each element in the list:

languages.forEach(IO::println);

It accepts a Consumer, a functional interface whose abstract method takes one argument and returns no value.

Referring to an existing method

The expression IO::println is a reference to the static println() method in java.lang.IO.

The double colon (::) separates the class name from the method name. The method reference does not call the method immediately. It supplies the action that forEach() invokes for each element.

This method reference can replace the following lambda expression:

languages.forEach(language -> IO.println(language));

Both versions print each language on a separate line, in list order.

Matching the functional interface

For this list, forEach() needs an action that accepts a string and returns no value.

IO.println(Object) is compatible because it accepts a String as an Object and returns void.

You do not add parentheses after the method name in a method reference:

IO::println

Parentheses belong to a method call, such as:

IO.println("Java");

Run the example

Compile and run the file:

javac MethodReferenceExample.java
java MethodReferenceExample

Output

Java
Python
JavaScript

Use a method reference when an existing method already performs the required action. Keep a lambda expression when you need additional logic, such as adding a prefix before printing each value.