Java Properties setProperty()

In this guide, you will learn about the Properties setProperty() method in Java programming and how to use it with an example.

1. Properties setProperty() Method Overview

Definition:

The setProperty() method of the Properties class in Java is utilized to set a property in the property list. It takes a key and a value, both of which are strings, and adds the property to the list. If the property already exists, the old value is replaced by the specified value.

Syntax:

public Object setProperty(String key, String value)

Parameters:

- key: The key to be placed into the property list.

- value: The value corresponding to the key.

Key Points:

- The setProperty() method is used to add a new property or update the value of an existing property in the property list.

- It returns the previous value of the specified key, or null if it did not have one.

- The Properties class provides a way to manage configuration or settings in an application, and setProperty() is a fundamental method to populate the property list.

- This method is thread-safe and can be used in concurrent environments.

2. Properties setProperty() Method Example

import java.util.Properties;

public class PropertiesSetPropertyExample {

    public static void main(String[] args) {
        Properties properties = new Properties();

        // Setting properties using setProperty() method
        properties.setProperty("database", "localhost");
        properties.setProperty("user", "admin");

        // Print the properties list
        System.out.println("Properties list: " + properties);

        // Update the existing property
        Object oldValue = properties.setProperty("user", "administrator");

        // Display the updated properties and the old value
        System.out.println("Updated Properties list: " + properties);
        System.out.println("Old Value: " + oldValue);
    }
}

Output:

Properties list: {database=localhost, user=admin}
Updated Properties list: {database=localhost, user=administrator}
Old Value: admin

Explanation:

In this example, a Properties object is created, and properties are set using the setProperty() method. The properties list is then printed to the console. Afterward, an existing property ("user") is updated to a new value, and the method returns the old value. The updated properties list and the old value of the updated property are then printed, demonstrating the usage and effect of the setProperty() method.

Comments