Properties Java

Properties Java

We know earlier Hashtable stores key/value pairs. There exists one more similar data structure that stores key/value pairs – Properties. Infact, Properties is derived from Hashtable. They differ very slightly. The key/value pair in Hasahtable can be objects of any Java class. But incase of Properties, the key/value pair should be strings only.

Following is the class signature

public class Properties extends Hashtable

As Properties is a subclass of Hashtable, it can utilize all the methods of Hashtable.

Two programs are given on Properties.

1. First program, PropMethods that use the methods of Properties.
2. Second program, PropSystem that reads system properties and prints.

The following is the first program using the Properties Java methods.

Properties Java

Properties prop = new Properties( );
prop.put("ten", "10");

A Properties object prop is created and added three key/value pairs with put() method, the same method we used in Hashtable. But here, key/value pairs must be strings only.

System.out.println("Value of ten: " + prop.getProperty("ten"));
System.out.println("Value of forty: " + prop.getProperty("forty"));

getProperty("ten") method returns 10, the value associated with key "ten". getProperty("forty") returns null as no key by name "forty" exists with prop object (we have not added it, infact).

The keys() method of Properties returns an object of Enumeration. Using the methods hasMoreElements() and nextElement() all the keys and values are printed. The working methodology of Enumeration is discussed very clearly in "Enumeration Interface".

2. Second program, PropSystem that reads system properties and prints.

The Properties Java object can best used to read system properties. Following program explains.

Properties Java

(Screenshot showing a part of program’s output)

Properties prop = System.getProperties();

getProperties() is a static method of System class that returns a Properties object containing all the properties of underlying (here, Windows) operating system. From Properties object prop, using Enumeration, all the keys (system property name) and values (corresponding value of the property) are printed. As the properties are many, a few are given in the screenshot.

One thought on “Properties Java

Leave a Reply

Your email address will not be published. Required fields are marked *