How to use the system clearProperty() function in Java

The clearProperty() function from java.lang.* in the System class removes the system property that is specified by the defined key.

Syntax


static String clearProperty(String key)

Parameters

clearProperty() takes a string type variable:

  • key: The name of the system property that has to be removed.

Return value

  • The clearProperty() function returns the string value previously linked with the system property.
  • This method returns null if there is no property with the defined key.
  • NullPointerException is thrown if the value of the key is null.
  • IllegalArgumentException is thrown if the key is empty.

Code

The code below demonstrates how the clearProperty() method works. Execute this code to see the output.

// Load basic classes
import java.lang.*;
public class EdPresso {
public static void main(String[] args) {
// IT WILL RETURN THE PREVIOUS VALUE REGARDING SYSTEM PROPERTY
System.out.println("the initial value is: " + System.getProperty("user.dir"));
// it will clear the value
String val = System.clearProperty("user.dir");
System.out.println("the returned value is: " + val);
System.out.println("the cleared result is: " + System.getProperty("user.dir"));
// setting the system property
System.setProperty("user.dir", "C:/java");
// getting the system property after making changes by using setProperty
System.out.println("the new value is: " + System.getProperty("user.dir"));
}
}

Explanation

In the code above, we use clearProperty() to display and remove the initial value of the system property. The return value of the function that stores the previous value is then displayed, which matches the initial value. A new value is set for the property and is displayed.