eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

When building command-line applications in Java, we may need to clear the console screen. This commonly arises when improving output readability, implementing simple interactive flows, or repeatedly refreshing information during program execution. In shell environments, clearing the screen is straightforward. However, the same task is less obvious when working within a Java application.

Java does not provide a native API for clearing the terminal. Thus, developers rely on indirect techniques that interact with the terminal in different ways. In practice, these techniques behave differently depending on the operating system, terminal emulator, and the environment used to run the application.

In this tutorial, we explore several ways to clear the console screen in Java while working on Ubuntu/Linux. First, we delve into why clearing the console is challenging in Java and how terminals interact with Java processes. Next, we examine three commonly used techniques and observe their behavior when executed in the terminal. Finally, we compare these approaches and discuss which options are appropriate for real-world Java CLI applications.

2. Understanding the Challenge

Clearing the console may appear simple at first glance, but Java is designed in a way that makes direct control of the terminal impossible. This limitation exists because Java applications do not own the terminal session.

Instead, the shell (for example, Bash) controls the terminal, while a Java program is merely a process writing to standard output and error streams. As a consequence, Java can only influence what it prints, not how the terminal itself behaves.

Let’s consider the following simple program that writes output to the console:

public class ClearConsoleScreen {

    public static void main(String[] args) {
        System.out.println("This text appears first.");
    }
}

When we run this program, the terminal shows text in our console:

This text appears first.

This represents the existing output already present in the terminal before we apply any clearing logic. In the following sections, we assume this output is visible and then observe how different clearing techniques affect the screen.

This distinction is important for several reasons:

  • Some approaches only manipulate the output produced by the Java process
  • Other approaches attempt to delegate control to external commands, such as clear
  • The behavior depends heavily on how the Java process launches and how the terminal interprets output

Because Java cannot directly control the terminal state, methods that appear similar in code can behave very differently in practice. Understanding this constraint helps explain why some techniques reliably clear the screen, while others only simulate the effect or behave inconsistently across environments.

3. Clearing the Console Using ANSI Escape Codes

Let’s look at an approach that works well for Java CLI applications on Linux:

public class ClearConsoleScreen {

    public static void clearWithANSICodes() {
        System.out.print("\033[H\033[2J");
        System.out.flush();
    }

    public static void main(String[] args) {
        clearWithANSICodes();
    }
}

As established in the previous section, the terminal already contains output before this method executes. When we run this program, the screen clears immediately, and the previous content is no longer visible:

[The terminal appears empty, with the cursor at the top-left corner]

The cursor moves to the top-left corner, and the terminal appears reset:

  • ANSI escape codes are interpreted directly by the terminal
  • No external process is created
  • No shell boundaries are crossed
  • The terminal state updates without leaving the Java process

Since this approach is predictable and does not depend on external commands or platform-specific tooling, it is well-suited for real-world Java CLI applications running in ANSI-compatible terminals.

4. Clearing the Console Using Blank Lines

Next, let’s clear the console using blank lines as our other alternative:

public class ClearConsoleScreen {

    public static void clearWithBlankLines() {
        for (int i = 0; i < 50; i++) {
            System.out.println();
        }
    }

    public static void main(String[] args) {
        clearWithBlankLines();
    }
}

Here, the original text scrolls out of view:

[Many blank lines, the previous output scrolls off the screen]

Even though the screen does not truly clear, the approach above can be useful for simple tools:

  • It works everywhere
  • No OS-specific behavior
  • No terminal features required

Although this approach does not technically clear the terminal buffer, it’s predictable. Since it relies only on printing standard output, it behaves the same across operating systems, terminal emulators, and build tools. For learning projects, logging-style applications, or simple scripts where visual perfection is not required, pushing content out of view can be entirely sufficient and avoids platform-specific logic.

5. Clearing the Console Using the OS Specific Command

Some developers may use operating system commands to clear the terminal. This method depends on the OS and runs the command as a separate process from Java.

5.1. Linux

Let’s clear the console using the Linux clear command:

public class ClearConsoleScreen {

    public static void clearWithLinuxCommand() {
        try {
            new ProcessBuilder("clear")
              .inheritIO()
              .start()
              .waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        clearWithLinuxCommand();
    }
}

Here, the terminal appears empty, with the cursor at the top-left corner:

  • clear runs as a child process
  • The terminal resets, but control remains with the Java process

This behavior often surprises developers because the clear command works perfectly when typed directly into the shell. However, when invoked from Java, it loses its shell-level control over the terminal and becomes just another child process. Once that process exits, control returns to the Java application, not to the shell. This makes it universally applicable to anyone running Java.

5.2. Windows

On Windows, the equivalent command is cls:

public class ClearConsoleScreen {

    public static void clearWithWindowsCommand() {
        try {
            new ProcessBuilder("cmd", "/c", "cls")
              .inheritIO()
              .start()
              .waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        clearWithWindowsCommand();
    }
}

Here, the terminal appears empty, with the cursor at the top-left corner. cls runs as a child process in a Windows command prompt.

Like Linux, the Java process itself doesn’t control the terminal; it simply delegates to the OS’s command.

6. Conclusion

In this article, we examined three commonly used techniques for clearing the console while running Java applications. We observed how each approach interacts differently with the terminal and how the execution context influences the final behavior.

Clearing the console screen in Java is a recurring requirement when building command-line applications, yet it remains non-trivial due to the lack of a native API and Java’s limited control over the terminal environment.

As demonstrated, no single technique works universally across all environments. Some methods depend on terminal support for escape sequences, while others rely on external commands or output manipulation, each with its own limitations. When choosing an approach, it’s important to consider the target platform, the execution environment, and whether the application is intended for simple output formatting or more interactive terminal usage. Understanding these constraints helps in selecting a solution that behaves predictably in practice.

The source code is over on GitHub.

Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)