Back

Explore Courses Blog Tutorials Interview Questions
+12 votes
5 views
in Java by (920 points)
I have output in my Java console from running an application, how I can i clear it using code ?

3 Answers

+13 votes
by (13.2k points)

In java, there is a function to clear console and not a command ,like in C++ there is a command :

system("CLS");

In java, there is a function :

public static void clearScreen() {  

   System.out.print("\033[H\033[2J");  

   System.out.flush();  

}

+1 vote
by (32.3k points)
edited by

Create a method in your class like this:

public static void clrscr(){

    //Clears Screen in java

    try {

        if (System.getProperty("os.name").contains("Windows"))

            new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();

        else

            Runtime.getRuntime().exec("clear");

    } catch (IOException | InterruptedException ex) {}

}

I haven’t checked this for Linux But this definitely works in Windows.

Want to learn Java end to end! Here's an informative video on Java:

Also, there is 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

0 votes
by
System.out.print("\f"); 

Paste the above code in your editor to clear the terminal screen when the program is running

Below is a sample code: 

public class ClearScreen
{
    public static void main(String args[])
    {
        for(int i = 1 ; i < 4 ; i++)
        {
            System.out.println("This code will get erased after it is printed " + (4-i) + " more time(s)"); 
            try
            {
                Thread.sleep(2000);
            }
            catch(Exception e)
            {    

            }
        }

        // code to clear screen 
        System.out.print("\f");
        
        // printing after erased
        System.out.println("Code was erased!!");
    }
}

Related questions

0 votes
1 answer
asked Jul 13, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.6k answers

500 comments

108k users

Browse Categories

...