Java Program to open computer application like notepad, calc etc.
Objective
Write a Java program to open an external computer application (Notepad, Calculator) from Java.
Algorithm / Approach
- Import
java.util.*. - Create a menu asking the user which program to open.
- Use the
ProcessBuilderclass, passing the executable name (e.g., "notepad.exe") to the constructor. - Call the
start()method on the ProcessBuilder object to launch the external application.
Test.java
import java.util.*;
class Test {
public static void main(String [] ar)
throws Exception {
ProcessBuilder np,calc;
np = new ProcessBuilder("notepad.exe");
calc = new ProcessBuilder("calc.exe");
String menu = "OPEN:\n";
menu += "Press 1 NOTEPAD\n";
menu += "Press 2 CALC\n";
menu += "------------\n";
menu += "Enter Choice: ";
System.out.print(menu);
Scanner sc = new Scanner(System.in);
int ch = sc.nextInt();
if(ch==1){
np.start();
System.out.println("NOTEPAD OPENED");
}
else if(ch==2){
calc.start();
System.out.println("CALC OPENED");
}
else{
System.out.println("INVALID CHOICE");
}
}
}
Expected Output
MENU: Press 1 NOTEPAD Press 2 CALC ------------ Enter Choice: 2 CALC OPENED
Explanation of the Program
- Java runs inside a Virtual Machine, but it can still communicate with the host Operating System.
ProcessBuilderallows your Java program to launch and manage native OS processes. Because "notepad.exe" is registered in the Windows system PATH, you don't need to provide the full file path to launch it.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)