Java Programming Tutorials

Java programming tutorials with many code examples!

Java System properties

Problem:

How to read Java System Properties? In the following example we show how to read single System property, list all, and use default when property is not defined.

Solution:

java.lang.System has a couple of methods that help to read System properties. They are:

  • Properties getProperties() Loads all system properties.
  • String getProperty(String key) Returns value of specified system property or null.
  • String getProperty(String key, String def) Returns value of specified system property or default value when not found.

All three methods are demonstrated in the following example:

package com.farenda.java.lang;

import java.util.Map.Entry;

public class SystemGetProperties {

    public static void main(String[] args) {
        // Get property value or null:
        System.out.println("Java version: "
                + System.getProperty("java.version"));

        System.out.println("Unknown property: "
                + System.getProperty("unknown.property"));

        // Use default if not found:
        System.out.println("\nConfig location: "
                + System.getProperty("config.location", "/tmp/config"));

        // List all system properties:
        System.out.println("\nSystem properties:");
        for (Entry<Object,Object> property : System.getProperties().entrySet()) {
            System.out.printf("%s: %s%n", property.getKey(), property.getValue());
        }
    }
}

Truncated result of running the above example:

Java version: 1.8.0_45
Unknown property: null

Config location: /tmp/config

System properties:
java.runtime.name: Java(TM) SE Runtime Environment
sun.boot.library.path: /usr/lib/jvm/java-8-oracle/jre/lib/amd64
java.vm.version: 25.45-b02
java.vm.vendor: Oracle Corporation
java.vendor.url: http://java.oracle.com/
path.separator: :
idea.launcher.port: 7533
java.vm.name: Java HotSpot(TM) 64-Bit Server VM
[...]

In the following posts we’ll dig dipper into Properties, so stay tuned! :-)

Share with the World!