Skip to main content

The System Class

The java.lang.System class contains several useful class fields and methods. It cannot be instantiated because its constructor is private. Among the facilities provided by the System class are standard input, standard output, and error output streams, as well as access to externally defined properties and environment variables.


1. Standard I/O Streams

The System class provides three standard streams that are heavily used for I/O operations in console applications:

  1. System.out: The standard output stream. It is typically used to print data to the console (e.g., System.out.println()).
  2. System.err: The standard error stream. It is used to print error messages. Like System.out, it prints to the console, but IDEs often highlight System.err output in red.
  3. System.in: The standard input stream. It is typically connected to the keyboard and is often wrapped in a Scanner object to read user input.
import java.util.Scanner;

public class LabSystem1 {

public static void main(String args[]) {
// 1. Standard Output
System.out.println("Normal Application Message");

// 2. Standard Error
System.err.println("Critical Error Message!");

// 3. Standard Input
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
int num = scanner.nextInt();
System.out.println("You entered: " + num);
}
}

2. Utility Methods

The System class provides several highly useful static utility methods.

System.exit(int status)

Terminates the currently running Java Virtual Machine (JVM).

  • The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.
  • System.exit(0) indicates successful termination.

System.currentTimeMillis()

Returns the current time in milliseconds. This is extremely useful for measuring the execution time of a block of code.

public class LabSystem2 {

public static void main(String args[]) {
long startTime = System.currentTimeMillis();

// Simulating some long-running task
for (int i = 0; i < 1000000; i++) {}

long endTime = System.currentTimeMillis();
System.out.println(
"Time taken: " + (endTime - startTime) + " milliseconds"
);
}
}

System.gc()

Runs the Garbage Collector.

  • Calling this method suggests that the Java Virtual Machine expend effort toward recycling unused objects to make the memory they currently occupy available for quick reuse.
  • However, it is only a suggestion; the JVM does not guarantee immediate execution of the Garbage Collector.

System.getenv()

Returns an unmodifiable string map view of the current system environment variables.

public class LabSystem3 {

public static void main(String args[]) {
// Getting the PATH environment variable
System.out.println("PATH = " + System.getenv("PATH"));
}
}