Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to clear the terminal/cmd screen.

Java Code Example — Utility Programs

ADVERTISEMENT

Java Program to clear the terminal/cmd screen.

Objective

Write a Java program to clear the terminal/command prompt screen.

Algorithm / Approach

  1. Determine the current OS using System.getProperty("os.name").
  2. If Windows: Use ProcessBuilder to run cmd /c cls. Use inheritIO() to attach the process to the current terminal, then start().waitFor().
  3. 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)
ADVERTISEMENT