System.setProperty() in Java

System.setProperty(): This method is available in java.lang.System class of Java.

Syntax:

String java.lang.System.setProperty(String key, String value)

This method takes two arguments of type String as its parameters. This method sets the system property indicated by the specified key.

Parameters: Two parameters are required for this method.

key: the name of the system property.value the value of the system property.

Returns: the previous value of the system property, or null if it did not have one.

Throws:

1. SecurityException - if a security manager exists and its checkPermission method doesn't allow setting of the specified property.

2. NullPointerException - if key or value is null.

3. IllegalArgumentException - if the key is empty.

Approach 1: When no exceptions.

Java

public class SystemsetProperty {
    public static void main(String[] args) {

        String key = "os.name";
        String value = "os.name";
        System.out.println(System.setProperty(key, value));
    }
}

Output:

Windows 10


Approach 2: NullPointerException

Java

public class SystemsetProperty {
    public static void main(String[] args) {

        String key = null;
        String value = "os.name";
        System.out.println(System.setProperty(key, value));
    }
}


Output:

Exception in thread "main" java.lang.NullPointerException: key can't be null at java.base/java.lang.System.checkKey(System.java:960) at java.base/java.lang.System.setProperty(System.java:908)



Approach 3: IllegalArgumentException

Java

public class SystemsetProperty {
    public static void main(String[] args) {

        String key = "";
        String value = "os.name";
        System.out.println(System.setProperty(key, value));
    }
}


Output:

Exception in thread "main" java.lang.IllegalArgumentException: key can't be empty at java.base/java.lang.System.checkKey(System.java:963) at java.base/java.lang.System.setProperty(System.java:908)


No comments:

Post a Comment