Java : System with Examples

System (Java SE 18 & JDK 18) API 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.

Class diagram

System.out.println("1234");
System.out.println("abcd");

// Result (The "standard" output stream.)
// ↓
//1234
//abcd
// Properties.
System.out.println(System.getProperty("java.specification.version")); // 18
System.out.println(System.getProperty("os.name")); // Windows 10
System.out.println(System.getProperty("file.encoding")); // UTF-8

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 : acded Enter
final var line = scanner.nextLine();

System.out.println(line); // abcde

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.)
// ↓
//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 : acde Enter
    // readPassword is 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); // 1644731803163

final var instant = Instant.ofEpochMilli(millis);
System.out.println(instant); // 2022-02-13T05:56:43.163Z

final var zoneId = ZoneId.systemDefault();
System.out.println(zoneId); // America/Los_Angeles

final var zonedDateTime = ZonedDateTime.ofInstant(instant, zoneId);
System.out.println(zonedDateTime); // 2022-02-12T21:56:43.163-08:00[America/Los_Angeles]

static void exit (int status)

Terminates the currently running 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");
    }
}

Result on 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.

System.gc();

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 (Excerpt)
// ↓
//...
//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.

final var logger = System.getLogger("com.example.lang.system");

logger.log(System.Logger.Level.INFO, "log test : 1");
logger.log(System.Logger.Level.INFO, "log test : 2");
logger.log(System.Logger.Level.INFO, "log test : 3");

// Result
// ↓
//Feb 12, 2022 9:40:31 PM com.example.lang.system.SystemEnTest getLogger
//INFO: log test : 1
//Feb 12, 2022 9:40:31 PM com.example.lang.system.SystemEnTest getLogger
//INFO: log test : 2
//Feb 12, 2022 9:40:31 PM com.example.lang.system.SystemEnTest getLogger
//INFO: log test : 3

static System.Logger getLogger (String name, ResourceBundle bundle)

Returns a localizable instance of Logger for the caller's use.

package com.example.lang.system;

import java.util.ListResourceBundle;

public class LoggerResourceEnBundle extends ListResourceBundle {

    @Override
    protected Object[][] getContents() {
        return new Object[][]{
                {"aaa", "XXX"}
        };
    }
}
final var bundle = ResourceBundle.getBundle("com.example.lang.system.LoggerResourceEnBundle");
final var logger = System.getLogger("com.example.lang.system", bundle);

logger.log(System.Logger.Level.INFO, "aaa");

// Result
// ↓
//Feb 12, 2022 9:41:58 PM com.example.lang.system.SystemEnTest getLogger_resourceBundle
//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 (Excerpt)
// ↓
//...
//java.specification.version : 18
//os.name : Windows 10
//file.encoding : UTF-8
//...

static String getProperty (String key)

Gets the system property indicated by the specified key.

System.out.println(System.getProperty("java.specification.version")); // 18
System.out.println(System.getProperty("os.name")); // Windows 10
System.out.println(System.getProperty("file.encoding")); // UTF-8

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.

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 s1 = new String("aaa");
final var s2 = new String("aaa");

System.out.println(s1 != s2); // true

System.out.println(s1.hashCode()); // 96321
System.out.println(s2.hashCode()); // 96321

System.out.println(System.identityHashCode(s1)); // 1551726463
System.out.println(System.identityHashCode(s2)); // 304216540

static Channel inheritedChannel ()

Returns the channel inherited from the entity that created this Java virtual machine.

final var channel = System.inheritedChannel();
System.out.println(channel); // null

More detail : SelectorProvider.inheritedChannel

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); // 14663375114900

Thread.sleep(1000);

final var end = System.nanoTime();
System.out.println(end); // 14664380610100

final var sec = (end - start) / 1000000000.0;
System.out.println(sec + " sec."); // 1.0054952 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("abcde");

System.out.println("outputStream : " + outputStream);

// Result
// ↓
//outputStream : abcde

static void setIn (InputStream in)

Reassigns the "standard" input stream.

final var bytes = "abcde\n".getBytes();

System.setIn(new ByteArrayInputStream(bytes));

final var scanner = new Scanner(System.in);
final var line = scanner.nextLine();

System.out.println(line); // abcde

static void setOut (PrintStream out)

Reassigns the "standard" output stream.

final var outputStream = new ByteArrayOutputStream();

System.setOut(new PrintStream(outputStream));
System.out.println("abcde");

System.err.println("outputStream : " + outputStream);

// Result
// ↓
//outputStream : abcde

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 (Excerpt)
// ↓
//...
//java.specification.version : 18
//os.name : Windows 10
//file.encoding : UTF-8
//...
//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.

Deprecated.


Related posts

To top of page