How to use Preferences API to store program configurations?

The Preferences API provided in the java.util.prefs package can be use to store and retrieve application configurations. The main class is the Preferences class. Using this class you can manage the preference data such as storing, retrieving, removing and clearing the preference data.

Preferences are key-value pairs of data. You can stored a string, int, boolean and other primitive data type. You can use the get() method to retrieve value associated with a key from preference node and the put() method to store a value associated with a key in the preference node. To remove a value associated with a key from preference node you can use the remove() method. And if you want to clear the keys from the preference node you can use the clear() method.

The actual storage of these preference data is dependent on the platform. For example in Windows OSes it stored in the Windows Registry. What you have to know that this Preferences API is not intended to use for storing application data, you will only use it to store configurations of your applications.

Let’s see an example of using the Preferences API.

Here are the output you’ll get when running the example above:

How to get random key-value pair from Hashtable?

How do I clear the content of an array?

In this example you’ll learn how to clear or reset the content of an array. We can use the java.util.Arrays.fill() method to replace to content of each element in the array. In the example below we create two arrays, names and numbers array. We initialize these arrays with some values and then clear the value by assigning null to each element of the array using the Arrays.fill() method.

The output of the code snippet: