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.

package org.kodejava.example.util.prefs;

import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;

public class PreferencesExample {
    public static void main(String[] args) {
        PreferencesExample demo = new PreferencesExample();
        demo.setPreferences();
    }

    private void setPreferences() {
        // Define a node to store the preferences data.
        Preferences pref = Preferences.userRoot().node(getClass().getName());

        String key1 = "KEY1";
        String key2 = "KEY2";
        String key3 = "KEY3";

        // Read the value of KEY1, return an empty string if the value
        // hasn't been set previously.
        String key1Value = pref.get(key1, "");
        System.out.println("KEY1: " + key1Value);

        // Read the value of KEY2 as an integer, if the value hasn't
        // been set previously return -1.
        int key2Value = pref.getInt(key2, -1);
        System.out.println("KEY2: " + key2Value);

        // Read the value of KEY3, return true if no value was set
        // previously.
        boolean key3Value = pref.getBoolean(key3, true);
        System.out.println("KEY3: " + key3Value);

        // Set the values for all of the preference key above.
        if (key1Value.equals("")) {
            pref.put(key1, "January");
        }
        if (key2Value == -1) {
            pref.putInt(key2, 1000);
        }
        if (key3Value) {
            pref.putBoolean(key3, false);
        }

        printKeys(pref);

        // Remove KEY1 from the preferences data.
        pref.remove(key1);
        printKeys(pref);

        try {
            // Remove all preference data of this node.
            pref.clear();
        } catch (BackingStoreException e) {
            e.printStackTrace();
        }

        printKeys(pref);
    }

    /**
     * Print Keys in the preferences node.
     * @param pref Preference node.
     */
    private void printKeys(Preferences pref) {
        System.out.println("PreferencesExample.printKeys");
        try {
            String[] keys = pref.keys();
            for (String key : keys) {
                System.out.println("Key = " + key);
            }
        } catch (BackingStoreException e) {
            e.printStackTrace();
        }
        System.out.println("============================");
    }
}

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

KEY1: 
KEY2: -1
KEY3: true
PreferencesExample.printKeys
Key = KEY1
Key = KEY2
Key = KEY3
============================
PreferencesExample.printKeys
Key = KEY2
Key = KEY3
============================
PreferencesExample.printKeys
============================

How to get random key-value pair from Hashtable?

package org.kodejava.example.util;

import java.util.Hashtable;
import java.util.Random;

public class HashtableGetRandom {
    public static void main(String[] args) {
        //
        // Create a hashtable and put some key-value pair.
        //
        Hashtable colors = new Hashtable();
        colors.put("black", "#000");
        colors.put("red", "#f00");
        colors.put("green", "#0f0");
        colors.put("blue", "#00f");
        colors.put("white", "#fff");

        //
        // Get a random entry from the hashtable.
        //
        Object[] keys = colors.keySet().toArray();
        Object key = keys[new Random().nextInt(keys.length)];
        System.out.println(key + " = " + colors.get(key));
    }
}

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.

package org.kodejava.example.util;

import java.util.Arrays;

public class ArrayClear {
    public static void main(String[] args) {
        String[] names = {"Alice", "Bob", "Carol"};
        System.out.println("names = " + Arrays.toString(names));

        //
        // Replace the contents of the names array to null for each array
        // element.
        //
        Arrays.fill(names, null);
        System.out.println("names = " + Arrays.toString(names));

        Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        System.out.println("numbers = " + Arrays.toString(numbers));
        
        //
        // Replace the contents of the numbers array to null for each
        // array element.
        //
        Arrays.fill(numbers, null);
        System.out.println("numbers = " + Arrays.toString(numbers));
    }
}

The output of the code snippet:

names = [Alice, Bob, Carol]
names = [null, null, null]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers = [null, null, null, null, null, null, null, null, null, null]

How do I validate input when using Scanner?

This example show you how to validate input when using java.util.Scanner. To validate input the Scanner class provides some hasNextXXX() method that can be use to validate input. For example if we want to check whether the input is a valid integer we can use the hasNextInt() method.

In the code snippet below will demonstrate how to validate whether the user provide a positive integer number. The program will repeat until the correct input is supplied.

package org.kodejava.example.util;

import java.util.Scanner;

public class ScannerValidateInput {
    public static void main(String[] args) {
        ScannerValidateInput demo = new ScannerValidateInput();
        demo.validatePositiveNumber();
    }

    private void validatePositiveNumber() {
        Scanner scanner = new Scanner(System.in);

        int number;
        do {
            System.out.print("Please enter a positive number: ");
            while (!scanner.hasNextInt()) {
                String input = scanner.next();
                System.out.printf("%s is not a valid number.\n", input);
            }
            number = scanner.nextInt();
        } while (number < 0);

        System.out.printf("You have entered a positive number %d.\n", number);
    }
}

The output produce by the snippet:

Please enter a positive number: 
qwerty
"qwerty" is not a valid number.
@@@
"@@@" is not a valid number.
-100
Please enter a positive number: 
99
You have entered a positive number 99.

How do I reverse the order of array elements?

In this code snippet you’ll learn how to reverse the order of array elements. To reverse to element order will be using the Collections.reverse() method. This method requires an argumet with List type. Because of this we need to convert the array to a List type first. We can use the Arrays.asList() to do the conversion. And then we reverse it. To convert the List back to array we can use the Collection.toArray() method.

Let’s see the code snippet below:

package org.kodejava.example.util;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ArrayReverse {
    public static void main(String[] args) {
        //
        // Creates an array of Integers and print it out.
        //
        Integer[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8};
        System.out.println("Arrays.toString(numbers) = " +
                Arrays.toString(numbers));

        //
        // Convert the int arrays into a List.
        //
        List numberList = Arrays.asList(numbers);

        //
        // Reverse the order of the List.
        //
        Collections.reverse(numberList);

        //
        // Convert the List back to arrays of Integers
        // and print it out.
        //
        numberList.toArray(numbers);
        System.out.println("Arrays.toString(numbers) = " +
                Arrays.toString(numbers));
    }
}

The output of the code snippet above is:

Arrays.toString(numbers) = [0, 1, 2, 3, 4, 5, 6, 7, 8]
Arrays.toString(numbers) = [8, 7, 6, 5, 4, 3, 2, 1, 0]