Java : System with Examples
System (Java SE 21 & JDK 21) with Examples.
You will find code examples on most System methods.
Summary
The System class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
System.out.println("1234");
System.out.println("abcd");
// Result (The "standard" output stream.)
// ↓
//1234
//abcd
final var ret1 = System.getProperty("java.specification.version");
System.out.println(ret1); // 21
final var ret2 = System.getProperty("os.name");
System.out.println(ret2); // Windows 10
Fields
static final PrintStream err
The "standard" error output stream.
System.err.println(1234);
System.err.println("abcd");
System.err.printf("num = %d", 789);
// Result (The "standard" error output.)
// ↓
//1234
//abcd
//num = 789
static final InputStream in
The "standard" input stream.
final var scanner = new Scanner(System.in);
// Input : abcd [Enter]
final var line = scanner.nextLine();
System.out.println(line); // abcd
static final PrintStream out
The "standard" output stream.
System.out.println(1234);
System.out.println("abcd");
System.out.printf("num = %d", 789);
// Result (The "standard" output stream.)
// ↓
//1234
//abcd
//num = 789
Methods
static void arraycopy (Object src, int srcPos, Object dest, int destPos, int length)
Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.
final int[] src = {1, 2, 3, 4};
final int[] dst1 = new int[4];
final int[] dst2 = new int[4];
final int[] dst3 = new int[4];
final int[] dst4 = new int[4];
System.out.println(Arrays.toString(src)); // [1, 2, 3, 4]
System.out.println(Arrays.toString(dst1)); // [0, 0, 0, 0]
System.out.println(Arrays.toString(dst2)); // [0, 0, 0, 0]
System.out.println(Arrays.toString(dst3)); // [0, 0, 0, 0]
System.out.println(Arrays.toString(dst4)); // [0, 0, 0, 0]
System.arraycopy(src, 0, dst1, 0, 4);
System.arraycopy(src, 0, dst2, 0, 3);
System.arraycopy(src, 0, dst3, 0, 2);
System.arraycopy(src, 0, dst4, 0, 1);
System.out.println(Arrays.toString(dst1)); // [1, 2, 3, 4]
System.out.println(Arrays.toString(dst2)); // [1, 2, 3, 0]
System.out.println(Arrays.toString(dst3)); // [1, 2, 0, 0]
System.out.println(Arrays.toString(dst4)); // [1, 0, 0, 0]
final int[] src = {1, 2, 3, 4};
final int[] dst1 = new int[4];
final int[] dst2 = new int[4];
final int[] dst3 = new int[4];
final int[] dst4 = new int[4];
System.arraycopy(src, 0, dst1, 0, 4);
System.arraycopy(src, 1, dst2, 0, 3);
System.arraycopy(src, 2, dst3, 0, 2);
System.arraycopy(src, 3, dst4, 0, 1);
System.out.println(Arrays.toString(dst1)); // [1, 2, 3, 4]
System.out.println(Arrays.toString(dst2)); // [2, 3, 4, 0]
System.out.println(Arrays.toString(dst3)); // [3, 4, 0, 0]
System.out.println(Arrays.toString(dst4)); // [4, 0, 0, 0]
final int[] src = {1, 2, 3, 4};
final int[] dst1 = new int[4];
final int[] dst2 = new int[4];
final int[] dst3 = new int[4];
final int[] dst4 = new int[4];
System.arraycopy(src, 0, dst1, 0, 4);
System.arraycopy(src, 0, dst2, 1, 3);
System.arraycopy(src, 0, dst3, 2, 2);
System.arraycopy(src, 0, dst4, 3, 1);
System.out.println(Arrays.toString(dst1)); // [1, 2, 3, 4]
System.out.println(Arrays.toString(dst2)); // [0, 1, 2, 3]
System.out.println(Arrays.toString(dst3)); // [0, 0, 1, 2]
System.out.println(Arrays.toString(dst4)); // [0, 0, 0, 1]
static String clearProperty (String key)
Removes the system property indicated by the specified key.
System.out.println(System.getProperty("aaa")); // null
System.out.println(System.setProperty("aaa", "bbb")); // null
System.out.println(System.getProperty("aaa")); // "bbb"
System.out.println(System.clearProperty("aaa")); // "bbb"
System.out.println(System.getProperty("aaa")); // null
static Console console ()
Returns the unique Console object associated with the current Java virtual machine, if any.
final var console = System.console();
if (console != null) {
// Input : abcd [Enter]
// The readPassword method reads a password or passphrase
// from the console with echoing disabled.
final var password = console.readPassword();
System.out.println(Arrays.toString(password)); // [a, b, c, d]
Arrays.fill(password, '\0');
System.out.println(Arrays.toString(password)); // [ , , , ]
}
static long currentTimeMillis ()
Returns the current time in milliseconds.
final var millis = System.currentTimeMillis();
System.out.println(millis); // 1714290837706
final var instant = Instant.ofEpochMilli(millis);
System.out.println(instant); // 2024-04-28T07:53:57.706Z
final var zoneId = ZoneId.systemDefault();
System.out.println(zoneId); // America/Los_Angeles
final var zonedDateTime = ZonedDateTime.ofInstant(instant, zoneId);
System.out.println(zonedDateTime); // 2024-04-28T00:53:57.706-07:00[America/Los_Angeles]
static void exit (int status)
Initiates the shutdown sequence of the Java Virtual Machine.
public class Main {
public static void main(String[] args) {
System.out.println("exit : before");
System.exit(999);
// This is not output.
System.out.println("exit : after");
}
}
// --- PowerShell ---
//PS R:\java-work> java Main
//exit : before
//
//PS R:\java-work> $LastExitCode
//999
static void gc ()
Runs the garbage collector in the Java Virtual Machine.
var sb = new StringBuilder("abcd");
final var ref = new WeakReference<>(sb);
System.out.println(ref.get()); // abcd
sb = null;
System.out.println(ref.get()); // abcd
System.gc();
System.out.println(ref.get()); // null
static Map<String,String> getenv ()
Returns an unmodifiable string map view of the current system environment.
final var envMap = System.getenv();
envMap.forEach((key, value) -> {
System.out.println(key + " : " + value);
});
// Result
// ↓
//...
//OS : Windows_NT
//PUBLIC : C:\Users\Public
//SESSIONNAME : Console
//...
static String getenv (String name)
Gets the value of the specified environment variable.
System.out.println(System.getenv("OS")); // Windows_NT
System.out.println(System.getenv("PUBLIC")); // C:\Users\Public
System.out.println(System.getenv("SESSIONNAME")); // Console
static System.Logger getLogger (String name)
Returns an instance of Logger for the caller's use.
public class Main {
public static void main(String[] args) {
final var logger = System.getLogger("com.example.system");
logger.log(System.Logger.Level.INFO, "TEST : 1");
logger.log(System.Logger.Level.INFO, "TEST : 2");
logger.log(System.Logger.Level.INFO, "TEST : 3");
}
}
// --- PowerShell ---
//PS R:\java-work> java Main
//Apr 28, 2024 3:47:31 PM Main main
//INFO: TEST : 1
//Apr 28, 2024 3:47:31 PM Main main
//INFO: TEST : 2
//Apr 28, 2024 3:47:31 PM Main main
//INFO: TEST : 3
static System.Logger getLogger (String name, ResourceBundle bundle)
Returns a localizable instance of Logger for the caller's use.
import java.util.ListResourceBundle;
public class LoggerResourceBundle extends ListResourceBundle {
@Override
protected Object[][] getContents() {
return new Object[][]{
{"aaa", "XXX"}
};
}
}
public class Main {
public static void main(String[] args) {
final var bundle = ResourceBundle.getBundle("LoggerResourceBundle");
final var logger = System.getLogger("com.example.system", bundle);
logger.log(System.Logger.Level.INFO, "aaa");
}
}
// --- PowerShell ---
//PS R:\java-work> java Main
//Apr 28, 2024 3:51:01 PM Main main
//INFO: XXX
static Properties getProperties ()
Determines the current system properties.
final var properties = System.getProperties();
properties.forEach((key, value) -> {
System.out.println(key + " : " + value);
});
// Result
// ↓
//...
//java.specification.version : 21
//os.name : Windows 10
//...
static String getProperty (String key)
Gets the system property indicated by the specified key.
final var ret1 = System.getProperty("java.specification.version");
System.out.println(ret1); // 21
final var ret2 = System.getProperty("os.name");
System.out.println(ret2); // Windows 10
static String getProperty (String key, String def)
Gets the system property indicated by the specified key.
System.out.println(System.getProperty("aaa")); // null
System.out.println(System.getProperty("aaa", "xxx")); // "xxx"
System.out.println(System.setProperty("aaa", "bbb")); // null
System.out.println(System.getProperty("aaa")); // "bbb"
System.out.println(System.getProperty("aaa", "xxx")); // "bbb"
static SecurityManager getSecurityManager ()
Deprecated, for removal: This API element is subject to removal in a future version. This method is only useful in conjunction with the Security Manager, which is deprecated and subject to removal in a future release.
Deprecated.
static int identityHashCode (Object x)
Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode().
final var list1 = new ArrayList<String>();
final var list2 = new ArrayList<String>();
list1.add("abc");
list2.add("abc");
System.out.println(list1 != list2); // true
System.out.println(list1.hashCode()); // 96385
System.out.println(list2.hashCode()); // 96385
System.out.println(System.identityHashCode(list1)); // 405896924
System.out.println(System.identityHashCode(list2)); // 1309335839
static Channel inheritedChannel ()
Returns the channel inherited from the entity that created this Java virtual machine.
More detail : SelectorProvider.inheritedChannel
final var channel = System.inheritedChannel();
System.out.println(channel); // null
static String lineSeparator ()
Returns the system-dependent line separator string.
// CR
System.out.println(Integer.toString('\r')); // 13
// LF
System.out.println(Integer.toString('\n')); // 10
final var separator = System.lineSeparator();
final var codePoints = separator.codePoints().toArray();
System.out.println(Arrays.toString(codePoints));
// Result on Windows.
// ↓
// [13, 10]
// Result on Linux.
// ↓
// [10]
static void load (String filename)
Loads the native library specified by the filename argument.
public class JniSample {
public native int sum(int a, int b);
}
For JNI (cpp)
JNIEXPORT jint JNICALL Java_JniSample_sum
(JNIEnv*, jobject, jint a, jint b) {
return a + b;
}
Create a DLL and place it to the below.
R:\java-work\lib\JniSample.dll
public class JniMain {
public static void main(String[] args) {
final var libPath = Path.of("R:", "java-work", "lib", "JniSample.dll");
System.out.println(libPath); // R:\java-work\lib\JniSample.dll
System.load(libPath.toString());
final var sample = new JniSample();
final var ret = sample.sum(100, 200);
System.out.println(ret); // 300
}
}
static void loadLibrary (String libname)
Loads the native library specified by the libname argument.
public class JniSample {
public native int sum(int a, int b);
}
For JNI (cpp)
JNIEXPORT jint JNICALL Java_JniSample_sum
(JNIEnv*, jobject, jint a, jint b) {
return a + b;
}
Create a DLL and place it to the below.
R:\java-work\lib\JniSample.dll
public class JniMain {
public static void main(String[] args) {
System.loadLibrary("JniSample");
final var sample = new JniSample();
final var ret = sample.sum(100, 200);
System.out.println(ret); // 300
}
}
java -D"java.library.path=R:\java-work\lib" JniMain
static String mapLibraryName (String libname)
Maps a library name into a platform-specific string representing a native library.
final var name = System.mapLibraryName("JniSample");
System.out.println(name);
// Result on Windows.
// ↓
// JniSample.dll
// Result on Linux.
// ↓
// libJniSample.so
static long nanoTime ()
Returns the current value of the running Java Virtual Machine's high-resolution time source, in nanoseconds.
final var start = System.nanoTime();
System.out.println(start); // 16097871697500
Thread.sleep(1000);
final var end = System.nanoTime();
System.out.println(end); // 16098873570100
// Displays elapsed seconds.
final var sec = (end - start) / 1000000000.0;
System.out.println(sec + " sec."); // 1.003872 sec.
static void runFinalization ()
Deprecated, for removal: This API element is subject to removal in a future version. Finalization has been deprecated for removal.
Deprecated.
static void setErr (PrintStream err)
Reassigns the "standard" error output stream.
final var outputStream = new ByteArrayOutputStream();
System.setErr(new PrintStream(outputStream));
System.err.println("abcd");
System.out.println("outputStream : " + outputStream);
// Result
// ↓
//outputStream : abcd
static void setIn (InputStream in)
Reassigns the "standard" input stream.
final var bytes = "abcd\n".getBytes();
System.setIn(new ByteArrayInputStream(bytes));
final var scanner = new Scanner(System.in);
final var line = scanner.nextLine();
System.out.println(line); // abcd
static void setOut (PrintStream out)
Reassigns the "standard" output stream.
final var outputStream = new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStream));
System.out.println("abcd");
System.err.println("outputStream : " + outputStream);
// Result
// ↓
//outputStream : abcd
static void setProperties (Properties props)
Sets the system properties to the Properties argument.
final var src = new Properties();
src.putAll(System.getProperties());
src.setProperty("aaa", "xxx");
src.setProperty("bbb", "yyy");
src.setProperty("ccc", "zzz");
System.setProperties(src);
final var dst = System.getProperties();
dst.forEach((key, value) -> System.out.println(key + " : " + value));
// Result
// ↓
//...
//java.specification.version : 21
//os.name : Windows 10
//...
//aaa : xxx
//bbb : yyy
//ccc : zzz
static String setProperty (String key, String value)
Sets the system property indicated by the specified key.
System.out.println(System.getProperty("aaa")); // null
System.out.println(System.setProperty("aaa", "bbb")); // null
System.out.println(System.getProperty("aaa")); // "bbb"
static void setSecurityManager (SecurityManager sm)
Deprecated, for removal: This API element is subject to removal in a future version. This method is only useful in conjunction with the Security Manager, which is deprecated and subject to removal in a future release.
Deprecated.