How do I get Java Home directory?

To get Java Home directory we can obtain it from system properties using the java.home key.

package org.kodejava.lang;

public class JavaHomeDirectory {
    public static void main(String[] args) {
        String javaHome = System.getProperty("java.home");
        System.out.println("JAVA HOME = " + javaHome);
    }
}

On my computer this code give me the following output:

JAVA HOME = C:\Program Files\Java\jdk-17

How do I get the username of operating system active user?

This example show you how to get operating system active user’s login name. We can obtain the username of current user by reading system properties using the user.name key.

package org.kodejava.lang;

public class GettingUserName {
    public static void main(String[] args) {
        String username = System.getProperty("user.name");
        System.out.println("username = " + username);
    }
}

How do I clear system property?

System.clearProperty(String key) method enables you to remove a system property. The key must not be an empty string or a null value because it will cause the method to throw an IllegalArgumentException or a NullPointerException.

It will also check if a SecurityManager exists and if you don’t have a write permission to the system property a SecurityException is going to be thrown.

package org.kodejava.lang;

public class ClearProperty {
    public static void main(String[] args) {
        String key = "user.dir";
        System.out.println(key + " = " + System.getProperty(key));

        // The System.clearProperty() method available since Java 1.5
        System.clearProperty(key);
        System.out.println(key + " = " + System.getProperty(key));
    }
}

The code snippet above give us the following output:

user.dir = F:\Wayan\Kodejava\kodejava-example
user.dir = null