There are several ways to clear the console in java but we will see the simplest code.
We pass command line interpreter(cmd) in the ProcessBuilder constructor to clear the console and the interpreter tells it to run a command that permits to call in-built commands (cls).
With the help of an example we will see the code of clearing the console are given below:
For Example:
import java.util.*;
class ClearConsole
{
public static void main(String[] args)
{
// Creates a LinkedList object
LinkedList ll = new LinkedList();
// To add an elements in LinkedList
ll.add("C");
ll.add("C++");
ll.add("PHP");
ll.add("JAVA");
// Display LinkedList on the Console
System.out.println("LinkedList = "+ll);
// Call clsConsole method
clsConsole();
}
// Create another static method named
// clsConsole that contains code of
// clearing console
public static void clsConsole(){
try{
new ProcessBuilder("cmd","/c","cls")
.inheritIO().start()
.waitFor();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
In the code above, we have created a LinkedList and added some elements in the list and then it displays LinkedList onto the console using output statement and then after we call clsConsole() method so it clear the console immediately.