Java Properties getProperty()

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

1. Properties getProperty() Method Overview

Definition:

The getProperty() method of the Properties class in Java is used to retrieve the value associated with a specified key in the property list. If the specified key is not found in the property list, this method returns null, or the default value specified as a parameter.

Syntax:

public String getProperty(String key)
public String getProperty(String key, String defaultValue)

Parameters:

- key: The property key whose associated value is to be returned.

- defaultValue: A default value to be returned if the key is not found in the property list.

Key Points:

- The getProperty() method returns the value associated with the specified key in the property list.

- If the key is not found, it returns null or the specified default value.

- It’s a convenient way to read configuration settings or other key-value pairs from properties files.

- The Properties class, where this method is housed, is a subclass of Hashtable and represents a persistent set of properties that can be loaded from or stored to a stream.

2. Properties getProperty() Method Example

import java.util.Properties;

public class PropertiesGetPropertyExample {

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

        // Adding some properties
        properties.setProperty("username", "admin");
        properties.setProperty("password", "admin123");

        // Retrieving properties using getProperty() method
        String username = properties.getProperty("username");
        String password = properties.getProperty("password");
        String unknown = properties.getProperty("unknown", "defaultValue");

        // Displaying the retrieved properties
        System.out.println("Username: " + username);
        System.out.println("Password: " + password);
        System.out.println("Unknown: " + unknown);
    }
}

Output:

Username: admin
Password: admin123
Unknown: defaultValue

Explanation:

In this example, a Properties object is created, and a couple of properties are added to it. 

The getProperty() method is then used to retrieve the values associated with the specified keys. For an unknown key, a default value is specified, which is returned as the key is not found in the property list. 

The output shows the retrieved values for the specified keys, verifying that the getProperty() method has worked as expected.

Comments