Properties example in Java

By: Jagan Emailed: 1768 times Printed: 2515 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the value is also a String. The Properties class is used by many other Java classes. For example, it is the type of object returned by System.getProperties() when obtaining environmental values.

Properties defines the following instance variable:

Properties defaults;

This variable holds a default property list associated with a Properties object. Properties defines these constructors:

Properties( )
Properties(Properties propDefault)

The first version creates a Properties object that has no default values. The second creates an object that uses propDefault for its default values. In both cases, the property list is empty.

Properties also contains one deprecated method: save(). This was replaced by store() because save() did not handle errors correctly.


One useful capability of the Properties class is that you can specify a default property that will be returned if no value is associated with a certain key. For example, a default value can be specified along with the key in the getProperty() method-such as getProperty("name", "default value"). If the "name" value is not found, then "default value" is returned. When you construct a Properties object, you can pass another instance of Properties to be used as the default properties for the new instance. In this case, if you call getProperty("foo") on a given Properties object, and "foo" does not exist, Java looks for "foo" in the default Properties object. This allows for arbitrary nesting of levels of default properties.

The following example demonstrates Properties. It creates a property list in which the keys are the names of states and the values are the names of their capitals. Notice that the attempt to find the capital for Florida includes a default value.

// Demonstrate a Property list.
import java.util.*;
class PropDemo {
public static void main(String args[]) {
Properties capitals = new Properties();
Set states;
String str;
capitals.put("Illinois", "Springfield");
capitals.put("Missouri", "Jefferson City");
capitals.put("Washington", "Olympia");
capitals.put("California", "Sacramento");
capitals.put("Indiana", "Indianapolis");
// Show all states and capitals in hashtable.
states = capitals.keySet(); // get set-view of keys
Iterator itr = states.iterator();
while(itr.hasNext()) {
str = (String) itr.next();
System.out.println("The capital of " +
str + " is " +
capitals.getProperty(str)
+ ".");
}
System.out.println();
// look for state not in list — specify default
str = capitals.getProperty("Florida", "Not Found");
System.out.println("The capital of Florida is "
+ str + ".");
}
}

The output from this program is shown here:

The capital of California is Sacramento.
The capital of Washington is Olympia.
The capital of Missouri is Jefferson City.
The capital of Indiana is Indianapolis.
The capital of Illinois is Springfield.
The capital of Florida is Not Found.
Since Florida is not in the list, the default value is used.

Although it is perfectly valid to use a default value when you call getProperty( ), as the preceding example shows, there is a better way of handling default values for most applications of property lists. For greater flexibility, specify a default property list when constructing a Properties object. The default list will be searched if the desired key is not found in the main list. For example, the following is a slightly reworked version of the preceding program, with a default list of states specified. Now, when Florida is sought, it will be found in the default list:

// Use a default property list.
import java.util.*;
class PropDemoDef {
public static void main(String args[]) {
Properties defList = new Properties();
defList.put("Florida", "Tallahassee");
defList.put("Wisconsin", "Madison");
Properties capitals = new Properties(defList);
Set states;
String str;
capitals.put("Illinois", "Springfield");
capitals.put("Missouri", "Jefferson City");
capitals.put("Washington", "Olympia");
capitals.put("California", "Sacramento");
capitals.put("Indiana", "Indianapolis");
// Show all states and capitals in hashtable.
states = capitals.keySet(); // get set-view of keys
Iterator itr = states.iterator();
while(itr.hasNext()) {
str = (String) itr.next();
System.out.println("The capital of " +
str + " is " +
capitals.getProperty(str)
+ ".");
}
System.out.println();
// Florida will now be found in the default list.
str = capitals.getProperty("Florida");
System.out.println("The capital of Florida is "
+ str + ".");
}
}


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(4)


1. View Comment

be very careful. use of put (or any method inherited from Hashtable) is discouraged. One should use setProperty method. This will insure that all arguments are Strings.

View Tutorial          By: d at 2009-10-14 09:55:23
2. View Comment

DOBN'T USE THIS SHIT
IT IS STRONGLY DISCOURAGED TO USE.

THIS IS WHAT ORACLE SAYS ABOUT THIS
Because Properties inherits from Hashtable, the put and putAll methods can be applied to a Properties object. Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are not Strings

http://download.oracle.com/javase/6/docs/api/java/util/Properties.html#setProperty%28java.lang.String,%20java.lang.String%29


View Tutorial          By: DD at 2011-09-13 13:00:30
3. View Comment

To DD -

The comment you just posted ("Their use is strongly discouraged") refers strictly to the "putAll" methods, not to the entire Properties class.

FYI, the Properties class is used everywhere in Java and it is safe to use it whenever you need it.


View Tutorial          By: Alex at 2011-09-30 10:36:11
4. View Comment

hi,
can you send me more examples regarding the properties class usage in real time projects........


View Tutorial          By: Ram M at 2015-10-05 06:32:27

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Jagan
Importing a Certificate for the CA example using keytool in Java
The if-then-else Statement in Java
WHERE Clauses in SQL
The TryCatchFinally Interface in JSP
assert() Function Example program in C
Guidelines for Struts Application Development
Using printf function in C
File Inclusion in C
Using Multiple Message Resource Bundles in Struts
While and For Loops in C
Arrays sample program in C
Controlling Page Navigation in JSF - Static and Dynamic Navigation
Using cout.fill() in C++
Types of Profiles in J2ME
DateField sample program in J2ME

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
InetAddress Example program in Java
Read from a COM port using Java program
Stack example in Java - push(), pop(), empty(), search()
How to use ArrayList in Java
The Basic Structure of a Simple Java program
Using StringTokenizer in Java
FileReader and FileWriter example program in Java
Transient vs Volatile modifiers in Java
Vector example in Java
Method Overriding in Java
Method Overloading (function overloading) in Java
instanceof sample program in Java
append() in Java
Student marks calculation program in Java
Reading from a file and writing to a file using Java program
Most Emailed Articles (in Java)
Text to Speech conversion program in Java
inheritance in Java
How to initialize an Array and how to copy the array
Using Charts in JasperReports
What is Unicode?
Operator Precedence in Java
Of Object, equals (), == and hashCode ()
DateFormat sample program in Java
A Simple whois program in Java
PushbackReader sample program in Java
CharArrayReader example program in Java
ByteArrayOutputStream - sample program in Java
Vector example in Java
Arrays example in Java - asList(), binarySearch(), fill(), sort(), equals()
HashSet Sample program in Java