Table of contents
1.
Introduction
2.
Fields
3.
Methods
4.
Common Use Cases
5.
Frequently Asked Questions
5.1.
What is the purpose of the System class in Java?
5.2.
How can I read user input using the System class?
5.3.
What is the difference between System.out & System.err?
6.
Conclusion
Last Updated: Nov 18, 2024
Easy

System Class in Java

Author Ravi Khorwal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The System class in Java is a fundamental part of the java.lang package and provides access to essential system operations. It offers a collection of static methods and variables that help us to interact with the Java runtime environment, retrieve system properties, perform memory management tasks, and access input/output streams. This class cannot be instantiated—which means you cannot create an object of it—because its methods are static, allowing direct access without needing an object. 

System Class in Java

In this article, we will discuss the main features of the System class, like its fields, methods, and common use cases.

Fields

The System class has many static final fields that represent standard input, output, and error streams. These fields are:

1. System.in: This field is an InputStream that represents the standard input stream. It is typically used to read input from the console or command line.
 

2. System.out: This field is a PrintStream that represents the standard output stream. It is used to write output to the console or command line.
 

3. System.err: This field is also a PrintStream, but it represents the standard error stream. It is used to write error messages or debugging information to the console or command line.

Methods

The System class provides a wide range of static methods that offer various functionalities. Let's discuss some of the commonly used methods:

1. static void arraycopy(Object source, int sourceStart, Object target, int targetStart, int size):

This method is used to copy elements from one array to another. It takes the source array, starting position in the source array, target array, starting position in the target array, & the number of elements to be copied as parameters.

Example:

int[] source = {1, 2, 3, 4, 5};
int[] target = new int[5];
System.arraycopy(source, 0, target, 0, 5);
// target will be {1, 2, 3, 4, 5}


2. static String getProperty(String key):

This method retrieves the system property specified by the given key. If the key is not found, it returns null.

Example:

String javaVersion = System.getProperty("java.version");
System.out.println("Java Version: " + javaVersion);


3. static void exit(int status):

This method terminates the currently running Java Virtual Machine (JVM) with the specified exit status. A non-zero status indicates an abnormal termination.

Example:

if (someCondition) {
    System.exit(1); // Terminate the JVM with status 1
}


4. static long currentTimeMillis():

This method returns the current time in milliseconds since January 1, 1970, 00:00:00 UTC.

Example:

long startTime = System.currentTimeMillis();
// Perform some operations
long endTime = System.currentTimeMillis();
long executionTime = endTime - startTime;
System.out.println("Execution Time: " + executionTime + "ms");


5. static void gc():

This method suggests to the JVM to perform garbage collection. However, the JVM does not guarantee immediate garbage collection upon calling this method.

Example:

System.gc(); // Suggest garbage collection to the JVM

 

6. static String clearProperty(String key):

This method removes the system property specified by the given key.

Example:

System.setProperty("myProperty", "value");
String removedValue = System.clearProperty("myProperty");
System.out.println("Removed Value: " + removedValue);


7. static String getProperty(String key, String def):

This method retrieves the system property specified by the given key. If the key is not found, it returns the default value provided.

Example:

String property = System.getProperty("myProperty", "defaultValue");
System.out.println("Property Value: " + property);


8. static String setProperty(String key, String value):

This method sets the system property specified by the given key to the specified value.

Example:

String oldValue = System.setProperty("myProperty", "newValue");
System.out.println("Old Value: " + oldValue);
System.out.println("New Value: " + System.getProperty("myProperty"));


9. static Console console():

This method returns the unique Console object associated with the current Java virtual machine, if any.

Example:

Console console = System.console();
if (console != null) {
    String input = console.readLine("Enter your input: ");
    console.printf("You entered: %s%n", input);
}


10. static Map<String, String> getenv():

This method returns an unmodifiable string map view of the current system environment.

Example:

Map<String, String> env = System.getenv();
for (String key : env.keySet()) {
    System.out.println(key + ": " + env.get(key));
}


11. static String getenv(String name):

This method retrieves the value of the specified environment variable.

Example:

String path = System.getenv("PATH");
System.out.println("PATH: " + path);


12. static Properties getProperties():

This method returns the system properties.

Example:

Properties properties = System.getProperties();
for (String key : properties.stringPropertyNames()) {
    System.out.println(key + ": " + properties.getProperty(key));
}


13. static void setProperties(Properties props):

This method sets the system properties to the specified properties.

Example:

Properties newProperties = new Properties();
newProperties.setProperty("myProperty", "value");
System.setProperties(newProperties);


14. static SecurityManager getSecurityManager():

This method returns the current security manager for the Java application environment.

Example:

SecurityManager securityManager = System.getSecurityManager();
if (securityManager != null) {
    System.out.println("Security Manager: " + securityManager.getClass().getName());
} else {
    System.out.println("No Security Manager set");
}


15. static void setSecurityManager(SecurityManager s):

This method sets the security manager for the Java application environment.

Example:

SecurityManager customSecurityManager = new CustomSecurityManager();
System.setSecurityManager(customSecurityManager);


16. static int identityHashCode(Object x):

This method returns the same hash code for the given object as would be returned by the default hash code method.

Example:

Object obj = new Object();
int hashCode = System.identityHashCode(obj);
System.out.println("Identity Hash Code: " + hashCode);


17. static Channel inheritedChannel():

This method returns the inherited channel from the creating process.

Example:

Channel inheritedChannel = System.inheritedChannel();
if (inheritedChannel != null) {
    System.out.println("Inherited Channel: " + inheritedChannel);
} else {
    System.out.println("No Inherited Channel");
}


18. static String lineSeparator():

This method returns the system-dependent line separator string.

Example:

String lineSeparator = System.lineSeparator();
System.out.println("Line 1" + lineSeparator + "Line 2");


19. static Logger getLogger(String name) and static Logger getLogger(String name, String bundle):

These methods return a logger for the specified name or resource bundle name.

Example:

Logger logger = System.getLogger("MyLogger");
logger.log(Level.INFO, "This is a log message");


20. static long freeMemory(), static long totalMemory(), and static long maxMemory():

These methods provide information about the memory usage of the Java Virtual Machine.

Example:

long freeMemory = System.freeMemory();
long totalMemory = System.totalMemory();
long maxMemory = System.maxMemory();

System.out.println("Free Memory: " + freeMemory + " bytes");
System.out.println("Total Memory: " + totalMemory + " bytes");
System.out.println("Max Memory: " + maxMemory + " bytes");


21. static Properties loadLibrary(String libname):

This method loads the specified native library.

Example:

System.loadLibrary("nativeLibrary");

Common Use Cases

The System class has many applications in many different situations. Let’s discuss few of the use cases where it might be useful: 

1. Reading User Input:

The System.in field, which represents the standard input stream, is commonly used to read user input from the console. It is often used in combination with the Scanner class to parse the input.


Example:

Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");


2. Writing Output:

The System.out field, representing the standard output stream, is used to write output to the console. It also provides methods like print() and println() to display text or values.

Example:

int result = 10;
System.out.println("The result is: " + result);


3. Logging & Error Handling:

The System.err field, representing the standard error stream, is often used for logging error messages or debugging information. It helps separate error output from regular output.

Example:

try {
    // Some code that may throw an exception
} catch (Exception e) {
    System.err.println("An error occurred: " + e.getMessage());
}


4. System Property Access:

The System class allows accessing system properties using methods like getProperty(). This is useful for retrieving information about the runtime environment, such as the Java version, operating system, or user home directory.

Example:

String osName = System.getProperty("os.name");
String userHome = System.getProperty("user.home");
System.out.println("Operating System: " + osName);
System.out.println("User Home Directory: " + userHome);


5. Performance Measurement:

The currentTimeMillis() and nanoTime() methods of the System class are commonly used to measure the execution time of code segments. They help with performance analysis and optimization.

Example:

long startTime = System.nanoTime();
// Code segment to measure
long endTime = System.nanoTime();
long duration = endTime - startTime;
System.out.println("Execution Time: " + duration + " nanoseconds");

Frequently Asked Questions

What is the purpose of the System class in Java?

The System class in Java provides access to system-related operations, such as standard input/output streams, system properties, & environment variables.

How can I read user input using the System class?

You can use the System.in field in combination with the Scanner class to read user input from the console.

What is the difference between System.out & System.err?

System.out is used for standard output, while System.err is used for error output. They both write to the console but can be redirected separately.

Conclusion

In this article, we discussed the System class in Java and its various features. We learned about the standard input/output streams, system properties, environment variables, and utility methods provided by the System class. With examples, we saw how to read user input, write output, access system properties, measure performance, and more. The System class proves to be a versatile tool for Java developers, which enables them to interact effectively with the runtime environment.

You can also check out our other blogs on Code360.

Live masterclass