Java is a versatile and powerful programming language known for its extensive standard library, which includes various classes and utilities for interacting with the system and managing application resources. One such essential class is the System
class. In this article, we’ll take a deep dive into the System
class, understand its significance, and explore its capabilities with practical examples.
The System
class is a fundamental part of Java’s core libraries, residing in the java.lang
package. It provides access to the system environment, system properties, and input/output streams.
Reading and Writing to Standard Streams
The System
class provides the following three standard I/O streams:
System.in
: This is an input stream (usually connected to the keyboard) that allows you to read data from the console.System.out
: This is an output stream (usually connected to the console) for printing data to the console.System.err
: This is an output stream (usually connected to the console) for printing error messages.
Time Measurement
public class Main {
public static void main(String[] args) {
long start=System.currentTimeMillis();
System.out.println(start);
}
}
Working with System Properties
public class Main {
public static void main(String[] args) {
String version=System.getProperty("java.version");
System.out.println(version); //21.0.1
String fileSeperator=System.getProperty("user.home");
System.out.println(fileSeperator); // /home/vboxuser
}
}
Environment Variable
public class Main {
public static void main(String[] args) {
String path= System.getenv("PATH");
System.out.println(path);
}
}