By sadia

2010-06-05 06:14:35 8 Comments

Can any body please tell me what code is used for clear screen in Java? For example in C++


What code is used in Java for clear screen?



@Dyndrilliac 2013-06-09 23:04:57

This is how I would handle it. This method will work for the Windows OS case and the Linux/Unix OS case (which means it also works for Mac OS X).

public final static void clearConsole()
        final String os = System.getProperty("");

        if (os.contains("Windows"))
    catch (final Exception e)
        //  Handle any exceptions.

Note that this method generally will not clear the console if you are running inside an IDE.

@Ben Leggiero 2014-10-21 20:30:12

On Windows 8.1: Cannot run program "cls": CreateProcess error=2, The system cannot find the file specified

@Dyndrilliac 2014-10-21 22:34:02

@BenLeggiero That error occurs if for some reason the cls command isn't found by the JVM within some directory from the PATH environment variable. All this code does is call the Windows or Unix system command based on the default system configuration to clear the command prompt or terminal window respectively. It should be exactly the same as opening a terminal window and typing "cls" followed by the Enter key.

@Ben Leggiero 2014-10-22 20:00:37

I know all this, but I figured it's worth noting that it can still fail. I don't know why it failed, but it obviously can.

@brainmurphy1 2014-11-05 00:22:13

were you testing it in the console of an IDE?

@danielcooperxyz 2014-12-03 11:42:01

For me testing it in an IDE it does not work and throws an exception. It also does not work when running it outside of the IDE from the command line on Windows 8.1 and Java 8.

@a_horse_with_no_name 2015-03-26 13:35:23

There is no cls executable in Windows. It is an internal command of cmd.exe.

@Holger 2015-10-27 22:55:03

As said by others, doesn’t work at all, not only because Windows has no cls executable, but also because the output of subprocesses gets redirected.

@Petter Friberg 2015-10-28 20:35:43

This answer is also a topic on meta see:…

@Abhishek Kashyap 2016-07-14 05:04:45

Create a method in your class like this: [as @Holger said here.]

public static void clrscr(){
    //Clears Screen in java
    try {
        if (System.getProperty("").contains("Windows"))
            new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
    } catch (IOException | InterruptedException ex) {}

This works for windows at least, I have not checked for Linux so far. If anyone checks it for Linux please let me know if it works (or not).

As an alternate method is to write this code in clrscr():

for(int i = 0; i < 80*300; i++) // Default Height of cmd is 300 and Default width is 80
    System.out.print("\b"); // Prints a backspace

I will not recommend you to use this method.

@satish 2015-08-30 11:19:25

You can use following code to clear command line console:

public static void clearScreen() {  

For further references visit:

@cossacksman 2015-11-03 00:24:11

Care to add to this at all? What is this string and do you need to flush if autoflush is enabled?

@jdurston 2015-11-12 20:01:28

They are ANSI escape codes. Specifically clear screen, followed by home. But why is 'home' necessary?

@Hugo Zink 2016-09-21 11:35:10

@jdurston omitting home will not reset the cursor back to the top of the window.

@Anh Tuan 2016-11-07 09:15:04

Doesn't work in Eclipse, but work in Linux terminal. One vote for you

@Thorbjørn Ravn Andersen 2017-09-17 23:16:21

This only works if the terminal emulator in which Java runs, supports ANSI escape codes. Windows NT/XP/7/8/10 CMD doesn't

@Eryk Sun 2019-01-16 19:27:44

@ThorbjørnRavnAndersen, you mean the Windows console. CMD is a shell, not a console or terminal.

@Thorbjørn Ravn Andersen 2019-01-17 11:41:03

@eryksun The thing that comes up when you ask Windows to invoke "CMD". If it can be invoked in a way that supports ANSI codes on all Windows machines, I'd love to hear about it.

@Eryk Sun 2019-01-17 11:57:41

@ThorbjørnRavnAndersen, CMD is a shell that uses a console, just like the bash shell in Linux uses a terminal. The difference with Windows is that executables can be flagged as console applications in the PE image header, in which case the process initialization code in kernelbase.dll will automatically attach to or allocate a console, depending on whether the parent has a console and whether the process creation flags override the default behavior by forcing no console (detached) or a new console. So people run CMD and see a console pop up, and then mistakenly think that CMD is the console.

@Eryk Sun 2019-01-17 12:01:27

@ThorbjørnRavnAndersen, as to virtual terminal support (i.e. VT escape codes), this was added to the console in Windows 10. In previous versions getting VT support requires an alternative console that hacks/hooks the console API, such as ConEmu or ANSICON.

@Thorbjørn Ravn Andersen 2019-01-17 12:07:44

@eryksun You may want to write that up in a full answer somewhere. Glad to hear it was added in Windows 10 - only been missing since NT 4.0 or something like that.

@Holger 2019-11-13 17:27:58

@ErykSun Windows 10 now supports ANSI codes, but enables them only for executables with a flag, for compatibility reasons. Since java.exe doesn’t have that flag, simple System.out.print statements still get no ANSI support. However, if you launch an executable or command that has that flag, e.g. a simple echo command, it works.

@Eryk Sun 2019-11-14 01:56:45

@Holger, if virtual terminal support isn't enabled, it's a simple matter to enable it via GetConsoleMode (get the current mode of the screen buffer) and SetConsoleMode to add the ENABLE_VIRTUAL_TERMINAL_PROCESSING flag. From Java there's the added complexity of JNI to call the latter functions. A user can also enable this setting globally in the console default settings in "HKCU\Console". Set a DWORD value of 1 as the "VirtualTerminalLevel".

@Holger 2019-11-14 08:35:08

@ErykSun which brings us back to square one, the absence of a simple Java solution.

@Matt 2020-02-03 15:05:48

I could not get the "clear" command to work via Java in the Vs code terminal on Linux, but this worked for me. Thanks!

@Abhigyan Singh 2016-04-02 06:26:06

This will work if you are doing this in Bluej or any other similar software.


@Bhuvanesh Waran 2016-10-14 10:42:49

Try the following :


This will work fine in Linux environment

@Holger 2015-10-27 22:40:31

Since there are several answers here showing non-working code for Windows, here is a clarification:


This command does not work, for two reasons:

  1. There is no executable named cls.exe or in a standard Windows installation that could be invoked via Runtime.exec, as the well-known command cls is builtin to Windows’ command line interpreter.

  2. When launching a new process via Runtime.exec, the standard output gets redirected to a pipe which the initiating Java process can read. But when the output of the cls command gets redirected, it doesn’t clear the console.

To solve this problem, we have to invoke the command line interpreter (cmd) and tell it to execute a command (/c cls) which allows invoking builtin commands. Further we have to directly connect its output channel to the Java process’ output channel, which works starting with Java 7, using inheritIO():


public class CLS {
    public static void main(String... arg) throws IOException, InterruptedException {
        new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();

Now when the Java process is connected to a console, i.e. has been started from a command line without output redirection, it will clear the console.

@Alist3r 2016-03-22 14:23:09

Why this not work for me? I running the program on windows CMD but the screen its not cleared

@Epic 2015-01-10 05:09:54

You can use an emulation of cls with for (int i = 0; i < 50; ++i) System.out.println();

@Sarz 2015-01-30 10:48:26

Its just a hint, maybe someone want to clear the screen, Actually

@Gyom 2015-02-06 13:07:40

@Sarz: and actually "clearing the screen" doesn't make proper sense by itself, either

@Denny 2014-09-30 16:47:02

You need to use JNI.

First of all use create a .dll using visual studio, that call system("cls"). After that use JNI to use this DDL.

I found this article that is nice:

@Denny 2015-04-30 14:36:10

That's work to me. I have a real project using JNI to clear the screen in JAVA.

@user3648739 2014-06-14 17:35:59

Runtime.getRuntime().exec(cls) did NOT work on my XP laptop. This did -

for(int clear = 0; clear < 1000; clear++)
     System.out.println("\b") ;

Hope this is useful

@DevilInDisguise 2016-02-05 18:12:37

if you could set the buffer index location to start this would be the sole easiest approach

@TrevorLee 2019-09-03 13:26:40

If the process was to get interrupted, I imagine you'd see lag with some print.out being removed before others.

@prunge 2013-01-19 01:50:57

If you want a more system independent way of doing this, you can use the JLine library and ConsoleReader.clearScreen(). Prudent checking of whether JLine and ANSI is supported in the current environment is probably worth doing too.

Something like the following code worked for me:

import jline.console.ConsoleReader;

public class JLineTest
    public static void main(String... args)
    throws Exception
        ConsoleReader r = new ConsoleReader();

        while (true)
            r.println("Good morning");

            String input = r.readLine("prompt>");

            if ("clear".equals(input))
            else if ("exit".equals(input))
                System.out.println("You typed '" + input + "'.");


When running this, if you type 'clear' at the prompt it will clear the screen. Make sure you run it from a proper terminal/console and not in Eclipse.

@blackløtus 2012-11-24 15:23:36

A way to get this can be print multiple end of lines ("\n") and simulate the clear screen. At the end clear, at most in the unix shell, not removes the previous content, only moves it up and if you make scroll down can see the previous content.

Here is a sample code:

for (int i = 0; i < 50; ++i) System.out.println();

@Ben Leggiero 2014-10-22 20:01:47

A faster way to accomplish this is printing a single string of 50 \r\n with a single println, since there's a noticeable delay between println calls.

@Cypher 2015-10-28 20:47:41

How do you know how many lines the console is configured to display? Might work in most cases, but not all.

@ndm13 2016-07-12 01:50:20

The biggest difference between this and a proper clear is that in the latter, the new output will be at the top of the screen and not the bottom.

@adeen-s 2017-02-26 16:46:02

I have to use 70 iterations to clear the screen completely.

@Aaron Esau 2017-12-30 00:28:05

System.out.println(new String(new char[50]).replace("\0", "\r\n")); will do the job faster and better.

@Holger 2019-11-13 17:30:40

@AaronEsau starting with JDK 11, you can use System.out.println(System.lineSeparator().repeat(50));

Related Questions

Sponsored Content

66 Answered Questions

[SOLVED] How do I generate random integers within a specific range in Java?

  • 2008-12-12 18:20:57
  • user42155
  • 4058563 View
  • 3505 Score
  • 66 Answer
  • Tags:   java random integer

87 Answered Questions

[SOLVED] Is Java "pass-by-reference" or "pass-by-value"?

32 Answered Questions

[SOLVED] When to use LinkedList over ArrayList in Java?

57 Answered Questions

[SOLVED] How to create a memory leak in Java?

23 Answered Questions

[SOLVED] What is a daemon thread in Java?

59 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

26 Answered Questions

23 Answered Questions

[SOLVED] Does Java support default parameter values?

42 Answered Questions

[SOLVED] "implements Runnable" vs "extends Thread" in Java

30 Answered Questions

[SOLVED] How to avoid Java code in JSP files?

  • 2010-07-05 07:24:06
  • chmoelders
  • 285585 View
  • 1673 Score
  • 30 Answer
  • Tags:   java jsp scriptlet

Sponsored Content