Java Program to clear the terminal/cmd screen.
Objective
Write a Java program to clear the terminal/command prompt screen.
Algorithm / Approach
- Determine the current OS using
System.getProperty("os.name"). - If Windows: Use
ProcessBuilderto runcmd /c cls. UseinheritIO()to attach the process to the current terminal, thenstart().waitFor(). - If Linux/Mac: Use
Runtime.getRuntime().exec("clear").
ClrScr.java
import java.util.*;
class ClrScr{
public static void main(String [] ar)
throws Exception {
String os = System.getProperty("os.name");
if (os.contains("Windows"))
{
ProcessBuilder pb;
pb=new ProcessBuilder("cmd","/c","cls");
pb.inheritIO().start().waitFor();
}
else
{
Runtime.getRuntime().exec("clear");
}
}
}
Expected Output
//SCREEN CLEAR
Explanation of the Program
- Unlike C or C++, Java does not have a built-in
clrscr()function because it is designed to be platform-independent (Windows uses "cls", Unix uses "clear"). - To achieve this, we must check the operating system at runtime and execute the native OS command to clear the screen buffer.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)