In Java, the System class provides a wide range of useful methods and properties to interact with the underlying operating system and manage various system-level operations. We will explore the methods offered by the System class and provide complete executable programs for each method, demonstrating their functionality. The System class cannot be instantiated since it only contains static fields and methods. It serves as a utility class that provides convenient access to system-related functionalities.
Exploring System Class Methods
arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
The arraycopy method is used to copy elements from one array to another. It is a powerful tool for efficiently transferring elements between arrays or within the same array.
Here’s an example program that demonstrates the usage of arraycopy:
public class Main {
public static void main(String[] args) {
int[] src = {1, 2, 3, 4, 5};
int[] dst = new int[5];
// Copy elements from src to dst
System.arraycopy(src, 0, dst, 0, src.length);
// Print the elements of dst
for (int element : dst)
System.out.println(element);
}
}
In the above program, we create a source array (src) with five elements and a destination array (dst) with the same size. We then use arraycopy to copy the elements from src to dst. Finally, we print the elements of dst.
clearProperty(String key)
The clearProperty method is used to remove a system property associated with the specified key.
Here’s an example program that demonstrates the usage of clearProperty:
public class Main {
public static void main(String[] args) {
// Set a system property
System.setProperty("coderscratchpad.url", "https://www.coderscratchpad.com");
// Get system property
String url = System.getProperty("coderscratchpad.url");
// Print url
System.out.println(url);
// Clear the system property
System.clearProperty("coderscratchpad.url");
// Check if the property exists
String propertyValue = System.getProperty("coderscratchpad.url");
if (propertyValue == null) {
System.out.println("Property 'coderscratchpad.url' is cleared.");
} else {
System.out.println("Property 'coderscratchpad.url' still exists.");
}
}
}
We set a system property with the key “coderscratchpad.url” and value “https://www.coderscratchpad.com”. Then, we use clearProperty to remove the property. Finally, we check if the property exists by retrieving its value using getProperty and display an appropriate message.
console()
The console method returns the unique Console object associated with the current Java virtual machine, if any.
Here’s an example program that demonstrates the usage of console:
import java.io.Console;
public class Main {
public static void main(String[] args) {
// Get the console object
Console console = System.console();
if (console != null) {
// Read a line of text from the user
String input = console.readLine("Enter your name: ");
// Print the user's input
console.printf("Hello, %s!", input);
} else {
System.out.println("No console available.");
}
}
}
In the above program, we use the console method to obtain the Console object. If the console object is not null, we prompt the user to enter their name and read the input using readLine. Then, we print a greeting message using printf. If the console object is null, we display a message indicating that no console is available.
currentTimeMillis()
The currentTimeMillis method returns the current time in milliseconds since the Unix epoch (January 1, 1970).
Here’s an example program that demonstrates the usage of currentTimeMillis:
public class Main {
public static void main(String[] args) {
// Get the current time in milliseconds
long currentTime = System.currentTimeMillis();
// Print the current time
System.out.println(currentTime);
}
}
In the above program, we use currentTimeMillis to obtain the current time in milliseconds and store it in the currentTime variable. Then, we print the current time using println.
exit(int status)
The exit method terminates the currently running Java virtual machine with the specified exit status.
Here’s an example program that demonstrates the usage of exit:
public class Main {
public static void main(String[] args) {
// Print a message
System.out.println("Before exit()");
// Terminate the JVM with exit status 0
System.exit(0);
// This line will not be executed
System.out.println("After exit()");
}
}
In the above program, we print a message before calling exit with the exit status 0. Once exit is invoked, the JVM terminates, and any code after exit will not be executed. The currentTimeMillis() method is often used for measuring elapsed time, benchmarking, or obtaining timestamps in applications. By calculating the difference between two calls to currentTimeMillis(), you can measure the execution time of a piece of code.
gc()
The gc method is a hint to the Java Virtual Machine (JVM) to run the garbage collector. The garbage collector is responsible for reclaiming memory occupied by objects that are no longer in use.
Here’s an example program that demonstrates the usage of gc:
public class Main {
public static void main(String[] args) {
// Create a large number of objects
for (int i = 0; i < 100000; i++) {
new Object();
}
// Run the garbage collector
System.gc();
System.out.println("Garbage collection triggered.");
}
}
In the above program, we create a large number of objects inside a loop. After that, we call gc to suggest that the garbage collector should run. Finally, we print a message to indicate that garbage collection has been triggered.
Please note that the invocation of gc does not guarantee immediate garbage collection. The JVM decides when and how to run the garbage collector based on various factors.
getenv()
The getenv() method returns a java.util.Map object that contains the current system environment variables as key-value pairs. Each key represents the name of an environment variable, and the corresponding value represents its value.
Here’s an example program that demonstrates the usage of getenv():
import java.util.Map;
public class Main {
public static void main(String[] args) {
// Retrieve all environment variables
Map<String, String> envVariables = System.getenv();
// Print all environment variables
for (Map.Entry<String, String> entry : envVariables.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + " = " + value);
}
}
}
In the above program, we call System.getenv() to retrieve all the environment variables as a Map. We then iterate over the map using a for-each loop and print each environment variable along with its value.
getenv(String name)
The getenv(String name) method is an overloaded version of getenv that retrieves the value of the specified environment variable with the given name.
Here’s an example program that demonstrates the usage of getenv(String name):
public class Main {
public static void main(String[] args) {
// Get the value of the "Path" environment variable
String path = System.getenv("Path");
// Print the value of the environment variable
System.out.println(path);
}
}
In the above program, we use getenv(“Path”) to retrieve the value of the “Path” environment variable, which represents the system’s search path for executable files. We store the value in the path variable and then print it.
You can replace “Path” with any valid environment variable name to retrieve its value.
getLogger(String name) and getLogger(String name, ResourceBundle bundle)
The getLogger methods return a logger with the specified name. They are part of the Java Logging API, which allows you to generate log messages during program execution.
Here’s an example program that demonstrates the usage of getLogger:
import java.util.logging.Logger;
public class Main {
// Create a logger for the current class
static Logger logger = Logger.getLogger(Main.class.getName());
public static void main(String[] args) {
logger.info("Logging an information message.");
logger.warning("Logging a warning message.");
}
}
In the above program, we create a logger using getLogger with the name of the current class. We then use the logger to log an information message and a warning message using info and warning methods, respectively.
You can customize the logger configuration and output format by modifying the logging properties file.
getProperties()
The getProperties method returns a Properties object that represents the current system properties.
Here’s an example program that demonstrates the usage of getProperties:
import java.util.Properties;
public class Main {
public static void main(String[] args) {
// Get the system properties
Properties properties = System.getProperties();
// Print all system properties
properties.forEach((key, value) -> {
System.out.println(key + " = " + value);
});
}
}
In the above program, we use getProperties to retrieve the system properties and store them in a Properties object. Then, we iterate over the properties using forEach and print each key-value pair.
This allows you to access and retrieve information about the current system configuration, such as the operating system, Java version, and more.
getProperty(String key)
The getProperty method retrieves the value of the system property associated with the specified key.
Here’s an example program that demonstrates the usage of getProperty:
public class Main {
public static void main(String[] args) {
// Get the value of the "os.name" system property
String osName = System.getProperty("os.name");
// Print the value of the system property
System.out.println(osName);
}
}
In the above program, we use getProperty to retrieve the value of the system property with the key “os.name”, which represents the name of the operating system on which the Java Virtual Machine (JVM) is running. We store the value in the osName variable and then print it.
You can replace “os.name” with any valid system property key to retrieve its value.
getProperty(String key, String def)
The getProperty(String key, String def) method is an overloaded version of getProperty that retrieves the value of the system property associated with the specified key. If the property is not found, it returns the default value provided.
Here’s an example program that demonstrates the usage of getProperty(String key, String def):
public class Main {
public static void main(String[] args) {
// Get the value of the "unknown.property" system property with a default value
String unknownProperty = System.getProperty("unknown.property", "Unknown");
// Print the value of the system property
System.out.println(unknownProperty);
}
}
In the above program, we use getProperty(“unknown.property”, “Unknown”) to retrieve the value of the system property with the key “unknown.property”. Since this property does not exist, the default value “Unknown” is returned. We store the value in the unknownProperty variable and then print it.
You can replace “unknown.property” with any valid system property key to retrieve its value or provide a different default value.
identityHashCode(Object x)
The identityHashCode method returns the identity hash code for the specified object. The identity hash code is typically derived from the object’s memory address and is used for low-level identity-based operations.
Here’s an example program that demonstrates the usage of identityHashCode:
public class Main {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Java";
// Get the identity hash codes of the strings
int hashCode1 = System.identityHashCode(str1);
int hashCode2 = System.identityHashCode(str2);
// Print the identity hash codes
System.out.println(hashCode1);
System.out.println(hashCode2);
}
}
In the above program, we create two string objects, str1 and str2. We then use identityHashCode to retrieve the identity hash codes of these objects and store them in hashCode1 and hashCode2 variables. Finally, we print the identity hash codes.
The identity hash code is not meant to be used as a general-purpose hash code for equality comparisons. It is primarily used for specialized cases that require identity-based operations.
inheritedChannel()
The inheritedChannel() method returns the inherited channel for the calling process. This method is typically used in scenarios where a child process needs to inherit the channel from its parent process.
Here’s an example program that demonstrates the usage of inheritedChannel():
import java.io.IOException;
import java.nio.channels.Channel;
public class Main {
public static void main(String[] args) {
// Get the inherited channel
try (Channel inheritedChannel = System.inheritedChannel()) {
if (inheritedChannel != null) {
// Check whether the channel is open
System.out.println(inheritedChannel.isOpen());
} else {
System.out.println("No inherited channel found.");
}
} catch (IOException e) {
// Handle IO Exceptions
System.out.println(e.getMessage());
}
}
}
In the above program, we use inheritedChannel() to retrieve the inherited channel for the current process. If an inherited channel exists, we check if it’s open; otherwise, we display a message indicating that no inherited channel was found.
Please note that the behavior of inheritedChannel() can vary depending on the operating system and process configuration.
lineSeparator()
The lineSeparator() method returns the system-dependent line separator string. This string represents the sequence of characters used to separate lines of text in files or output streams.
Here’s an example program that demonstrates the usage of lineSeparator():
public class Main {
public static void main(String[] args) {
// Get the system-dependent line separator
String lineSeparator = System.lineSeparator();
// Print the line separator
System.out.println(lineSeparator);
}
}
In the above program, we use lineSeparator() to retrieve the line separator string specific to the underlying system. We store the string in the lineSeparator variable and then print it.
By using lineSeparator() instead of hard-coding newline characters (“\n”) in your code, you ensure platform independence and compatibility.
load(String filename)
The load(String filename) method loads a library specified by the filename argument. This method is used to dynamically load native libraries into a Java program.
Here’s an example program that demonstrates the usage of load(String filename):
public class Main {
public static void main(String[] args) {
// Load the library "dll"
System.load("abspath/to/library.dll");
// Use the loaded library
}
}
In the above program, we use load to load the native library named “library” from the specified file path. After loading the library, you can use its functions or interact with it in your Java code.
Please note that the library file path must be specified correctly, including the file extension (“.so” for Linux/Unix, “.dll” for Windows).
loadLibrary(String libname)
The loadLibrary(String libname) method loads the system library specified by the libname argument. This method is used to load system libraries that are identified by their platform-specific names.
Here’s an example program that demonstrates the usage of loadLibrary(String libname):
public class Main {
public static void main(String[] args) {
// Load the system library "library"
System.loadLibrary("library");
// Use the loaded library
}
}
In the above program, we use loadLibrary to load the system library “library”. The library name is platform-dependent, so the appropriate library file for the current platform will be loaded.
Please ensure that the system library is present and accessible in the system’s library path.
mapLibraryName(String libname)
The method takes a libname parameter, which represents the base name of the library without any platform-specific prefixes or extensions. It returns a String that represents the platform-specific name of the library, including the appropriate prefix and file extension.
The mapping of the library name depends on the underlying operating system. For example, on different platforms, the library name might have different prefixes or extensions. Here’s an example that demonstrates the usage of the mapLibraryName() method:
public class Main {
public static void main(String[] args) {
// Specify the base name of the library
String baseName = "library";
// Map the library name to the platform-specific name
String mappedName = System.mapLibraryName(baseName);
// Print the platform-specific library name
System.out.println(mappedName);
}
}
When you run this code on different platforms, it will return the platform-specific library name based on the underlying operating system. For example:
- On Windows, it might return “library.dll”.
- On macOS, it might return “liblibrary.dylib”.
- On Linux, it might return “liblibrary.so”.
Please note that the specific output will depend on the operating system you are running your Java program on. The mapLibraryName() method is useful when you need to load platform-specific native libraries dynamically using the System.loadLibrary() method.
nanoTime()
The nanoTime() method returns the current value of the running Java Virtual Machine’s high-resolution time source, in nanoseconds. This method can be used for measuring elapsed time with high precision.
Here’s an example program that demonstrates the usage of nanoTime():
public class Main {
public static void main(String[] args) {
long startTime = System.nanoTime();
// Perform some time-consuming operation
long endTime = System.nanoTime();
long elapsedTime = endTime - startTime;
System.out.println("Elapsed Time: " + elapsedTime + " nanoseconds");
}
}
In the above program, we use nanoTime() to capture the starting time before performing a time-consuming operation. Then, we capture the ending time after the operation is complete. By subtracting the starting time from the ending time, we obtain the elapsed time in nanoseconds. Finally, we print the elapsed time.
The nanoTime() method is useful for precise timing measurements, especially when dealing with small time intervals or performance-sensitive code.
setErr(PrintStream err)
The setErr(PrintStream err) method reassigns the “standard” error output stream to the specified PrintStream object. This allows redirecting error messages to a custom output stream.
Here’s an example program that demonstrates the usage of setErr(PrintStream err):
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class Main {
public static void main(String[] args) {
try {
// Create a custom error output stream
PrintStream errorStream = new PrintStream("error.log");
// Redirect the error output to the custom stream
System.setErr(errorStream);
// Simulate an error
throw new FileNotFoundException("File not found");
} catch (FileNotFoundException e) {
// Error message will be redirected to the custom stream
e.printStackTrace();
}
}
}
In the above program, we create a custom PrintStream object called errorStream, which is initialized with a file name “error.log”. We then redirect the error output by calling setErr(errorStream), assigning our custom stream as the new error output stream. When an exception occurs (in this case, a FileNotFoundException), the error message will be redirected to the custom stream. Finally, we print the stack trace to the error stream using e.printStackTrace().
This technique can be useful when you want to capture and handle error messages separately or log them to a specific location.
setIn(InputStream in) and setOut(PrintStream out)
The setIn(InputStream in) and setOut(PrintStream out) methods allow redirecting the “standard” input and output streams to custom streams, respectively. This enables customization of input and output sources in a Java program.
Here’s an example program that demonstrates the usage of setIn(InputStream in) and setOut(PrintStream out):
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Create a custom input stream with predefined data
String inputString = "Hello, Java!";
InputStream inputStream = new ByteArrayInputStream(inputString.getBytes());
// Create a custom output stream to capture the output
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PrintStream printStream = new PrintStream(outputStream);
// Redirect the input and output streams
System.setIn(inputStream);
System.setOut(printStream);
// Read from the custom input stream
Scanner scanner = new java.util.Scanner(System.in);
String input = scanner.nextLine();
// Print to the custom output stream
System.out.println(input);
// Retrieve the captured output
String output = outputStream.toString();
// Print the captured output
System.out.println(output);
}
}
In the above program, we create a custom InputStream object called inputStream with the data “Hello, Java!”. We also create a custom ByteArrayOutputStream object called outputStream to capture the output. Then, we create a PrintStream object printStream initialized with the outputStream.
Next, we redirect the standard input stream using System.setIn(inputStream) and the standard output stream using System.setOut(printStream).
We read from the custom input stream using Scanner and store the input in the input variable. We then print a message to the custom output stream using System.out.println(input).
Finally, we retrieve the captured output from the outputStream and print it using System.out.println(output).
This technique can be useful when you want to programmatically simulate user input or capture program output for testing or logging purposes.
setProperties(Properties props)
The setProperties(Properties props) method sets the system properties to the specified Properties object. This allows you to customize the system properties programmatically.
Here’s an example program that demonstrates the usage of setProperties(Properties props):
import java.util.Properties;
public class Main {
public static void main(String[] args) {
// Create a Properties object and set custom properties
Properties customProps = new Properties();
customProps.setProperty("custom.property1", "value1");
customProps.setProperty("custom.property2", "value2");
// Set the custom properties as system properties
System.setProperties(customProps);
// Access the custom properties
String prop1 = System.getProperty("custom.property1");
String prop2 = System.getProperty("custom.property2");
// Print the custom properties
System.out.println(prop1);
System.out.println(prop2);
}
}
In the above program, we create a Properties object called customProps and set two custom properties using the setProperty method. Then, we call System.setProperties(customProps) to set these custom properties as system properties.
After setting the properties, we can access and retrieve their values using System.getProperty(key). In this example, we retrieve the values of the custom properties we set and print them.
Setting custom properties can be useful for configuring application-specific settings or passing parameters to your program.
setProperty(String key, String value)
The setProperty(String key, String value) method sets the system property specified by the key to the provided value. It allows you to modify or define system properties programmatically.
Here’s an example program that demonstrates the usage of setProperty(String key, String value):
public class Main {
public static void main(String[] args) {
// Set a system property
System.setProperty("custom.property", "custom-value");
// Retrieve the system property
String prop = System.getProperty("custom.property");
// Print the system property
System.out.println(prop);
}
}
In the above program, we use setProperty to set a custom system property with the key “custom.property” and value “custom-value”. We then retrieve the value of the property using System.getProperty and print it.
Modifying system properties can be useful for various purposes, such as configuring application behavior or providing runtime parameters.
Conclusion
The System class in Java provides essential functionalities for system-related operations, environment interaction, and logging. Throughout this exploration, we covered methods like arraycopy for array manipulation, currentTimeMillis and nanoTime for time measurement, and exit for program termination.
We also discussed techniques for garbage collection, obtaining system properties, accessing and retrieving environment variables, and customizing input, output, and error streams. Additionally, we explored logging capabilities and mapping library names to platform-specific equivalents.
By mastering the System class and its methods, developers can efficiently handle system tasks, customize behavior, and log application messages. Keep the Java API documentation as a valuable resource, and continue to explore and experiment with the vast capabilities of the System class.
Sources
I hope you found this information informative. If you would like to receive more content, please consider subscribing to our newsletter!