The Wayback Machine - https://web.archive.org/web/20240907055742/https://www.geeksforgeeks.org/java-util-properties-class-java/
Open In App

Properties Class in Java

Last Updated : 24 Nov, 2020
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. It belongs to java.util package. Properties define the following instance variable. This variable holds a default property list associated with a Properties object. 

Properties defaults: This variable holds a default property list associated with a Properties object.
 

Features of Properties class:

  • Properties is a subclass of Hashtable.
  • It is used to maintain a list of values in which the key is a string and the value is also a string i.e; it can be used to store and retrieve string type data from the properties file.
  • Properties class can specify other properties list as it’s the default. If a particular key property is not present in the original Properties list, the default properties will be searched.
  • Properties object does not require external synchronization and Multiple threads can share a single Properties object.
  • Also, it can be used to retrieve the properties of the system.

Advantage of a Properties file

In the event that any data is changed from the properties record, you don’t have to recompile the java class. It is utilized to store data that is to be changed habitually.

Note: The Properties class does not inherit the concept of a load factor from its superclass, Hashtable.

Declaration

public class Properties extends Hashtable<Object,​Object>

Constructors of Properties 

1. Properties(): This creates a Properties object that has no default values. 

Properties p = new Properties();

2. Properties(Properties propDefault): The second creates an object that uses propDefault for its default value. 

Properties p = new Properties(Properties propDefault);

Example 1: The below program shows how to use Properties class to get information from the properties file. 

Let us create a properties file and name it as db.properties.

db.properties

username = coder
password = geeksforgeeks

Code

Java




// Java program to demonstrate Properties class to get
// information from the properties file
  
import java.util.*;
import java.io.*;
public class GFG {
    public static void main(String[] args) throws Exception
    {
        // create a reader object on the properties file
        FileReader reader = new FileReader("db.properties");
  
        // create properties object
        Properties p = new Properties();
  
        // Add a wrapper around reader object
        p.load(reader);
  
        // access properties data
        System.out.println(p.getProperty("username"));
        System.out.println(p.getProperty("password"));
    }
}


Output

print properties of a file

Example 2: The below program shows how to use the Properties class to get all the system properties. Using System.getProperties() method, we can get all the properties of the system.

Java




// Java program to demonstrate Properties class to get all
// the system properties
  
import java.util.*;
import java.io.*;
  
public class GFG {
    public static void main(String[] args) throws Exception
    {
        // get all the system properties
        Properties p = System.getProperties();
  
        // stores set of properties information
        Set set = p.entrySet();
  
        // iterate over the set
        Iterator itr = set.iterator();
        while (itr.hasNext()) {
  
            // print each property
            Map.Entry entry = (Map.Entry)itr.next();
            System.out.println(entry.getKey() + " = "
                               + entry.getValue());
        }
    }
}


Output

get all the system properties

Example 3: The below program shows how to use the Properties class to create a properties file.

Java




// Java program to demonstrate Properties class to create
// the properties file
  
import java.util.*;
import java.io.*;
  
public class GFG {
    public static void main(String[] args) throws Exception
    {
        // create an instance of Properties
        Properties p = new Properties();
  
        // add properties to it
        p.setProperty("name", "Ganesh Chowdhary Sadanala");
        p.setProperty("email",
                      "ganeshs.gfg@gmail.com");
  
        // store the properties to a file
        p.store(new FileWriter("info.properties"),
                "GeeksforGeeks Properties Example");
    }
}


Output

use Properties class to create a properties file.

Methods of Properties

METHOD

DESCRIPTION

getProperty​(String key) Searches for the property with the specified key in this property list.
getProperty​(String key, String defaultValue) Searches for the property with the specified key in this property list.
list​(PrintStream out) Prints this property list out to the specified output stream.
list​(PrintWriter out) Prints this property list out to the specified output stream.
load​(InputStream inStream) Reads a property list (key and element pairs) from the input byte stream.
load​(Reader reader) Reads a property list (key and element pairs) from the input character stream in a simple line-oriented format.
loadFromXML​(InputStream in) Loads all of the properties represented by the XML document on the specified input stream into this properties table.
propertyNames() Returns an enumeration of all the keys in this property list, including distinct keys in the default property list if a key of the same name has not already been found from the main properties list.
save​(OutputStream out, String comments)

Deprecated.

This method does not throw an IOException if an I/O error occurs while saving the property list.

setProperty​(String key, String value) Calls the Hashtable method put.
store​(OutputStream out, String comments) Writes this property list (key and element pairs) in this Properties table to the output stream in a format suitable for loading into a Properties table using the load(InputStream) method.
store​(Writer writer, String comments) Writes this property list (key and element pairs) in this Properties table to the output character stream in a format suitable for using the load(Reader) method.
storeToXML​(OutputStream os, String comment) Emits an XML document representing all of the properties contained in this table.
storeToXML​(OutputStream os, String comment, String encoding) Emits an XML document representing all of the properties contained in this table, using the specified encoding.
storeToXML​(OutputStream os, String comment, Charset charset) Emits an XML document representing all of the properties contained in this table, using the specified encoding.
stringPropertyNames() Returns an unmodifiable set of keys from this property list where the key and its corresponding value are strings, including distinct keys in the default property list if a key of the same name has not already been found from the main properties list.

Methods declared in class java.util.Hashtable

METHOD

DESCRIPTION

clear() Clears this hashtable so that it contains no keys.
 clone() Creates a shallow copy of this hashtable.
compute​(K key, BiFunction<? super K,​? super V,​? extends V> remappingFunction) Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
computeIfAbsent​(K key, Function<? super K,​? extends V> mappingFunction) If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
computeIfPresent​(K key, BiFunction<? super K,​? super V,​? extends V> remappingFunction) If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
contains​(Object value) Tests if some key maps into the specified value in this hashtable.
containsKey​(Object key) Tests if the specified object is a key in this hashtable.
containsValue​(Object value) Returns true if this hashtable maps one or more keys to this value.
elements() Returns an enumeration of the values in this hashtable.
entrySet() Returns a Set view of the mappings contained in this map.
equals​(Object o) Compares the specified Object with this Map for equality, as per the definition in the Map interface.
get​(Object key) Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
hashCode() Returns the hash code value for this Map as per the definition in the Map interface.
isEmpty() Tests if this hashtable maps no keys to values.
keys() Returns an enumeration of the keys in this hashtable.
keySet() Returns a Set view of the keys contained in this map.
merge​(K key, V value, BiFunction<? super V,​? super V,​? extends V> remappingFunction) If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
put​(K key, V value) Maps the specified key to the specified value in this hashtable.
putAll​(Map<? extends K,​? extends V> t) Copies all of the mappings from the specified map to this hashtable.
rehash() Increases the capacity of and internally reorganizes this hashtable, in order to accommodate and access its entries more efficiently.
remove​(Object key) Removes the key (and its corresponding value) from this hashtable.
size() Returns the number of keys in this hashtable.
toString() Returns a string representation of this Hashtable object in the form of a set of entries, enclosed in braces and separated by the ASCII characters ” , ” (comma and space).
values() Returns a Collection view of the values contained in this map.

Methods declared in interface java.util.Map

METHOD

DESCRIPTION

forEach​(BiConsumer<? super K,​? super V> action) Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.
getOrDefault​(Object key, V defaultValue) Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
putIfAbsent​(K key, V value) If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
remove​(Object key, Object value) Removes the entry for the specified key only if it is currently mapped to the specified value.
replace​(K key, V value) Replaces the entry for the specified key only if it is currently mapped to some value.
replace​(K key, V oldValue, V newValue) Replaces the entry for the specified key only if currently mapped to the specified value.
replaceAll​(BiFunction<? super K,​? super V,​? extends V> function) Replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.


Similar Reads

Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.Class class in Java | Set 2
Java.lang.Class class in Java | Set 1 More methods: 1. int getModifiers() : This method returns the Java language modifiers for this class or interface, encoded in an integer. The modifiers consist of the Java Virtual Machine's constants for public, protected, private, final, static, abstract and interface. These modifiers are already decoded in Mo
15+ min read
Properties clone() method in Java with Examples
The Java.util.Properties.clone() method is used to create a shallow copy of this instance with all the elements from this Properties instance. Syntax: public Object clone() Parameters: The method does not take any parameter Return Value: The function returns the cloned Object which is the shallow copy of this Properties instance. Below programs ill
2 min read
Properties clear() method in Java with Examples
The Java.util.Properties.clear() method is used to remove all the elements from this Properties instance. Using the clear() method only clears all the element from the Properties and does not delete the Properties. In other words, we can say that the clear() method is used to only empty an existing Properties. Syntax: public void clear() Parameters
2 min read
Properties computeIfPresent(Key, BiFunction) method in Java with Examples
The computeIfPresent(Key, BiFunction) method of Properties class which allows you to compute value of a mapping for specified key if key is already associated with a value (or is mapped to null). If mapping function of this method returns null, the mapping is removed. If the remapping function throws an exception, the exception is rethrown, and the
2 min read
Properties computeIfAbsent(Key, Function) method in Java with Examples
The computeIfAbsent(Key, Function) method of Properties class which allows you to compute value of a mapping for specified key if key is not already associated with a value (or is mapped to null). If mapping function of this method returns null, then no mapping is recorded. If the remapping function throws an exception, the exception is rethrown, a
2 min read
Properties compute(Key, BiFunction) method in Java with Examples
The compute(Key, BiFunction) method of Properties class allows to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping is found). If the remapping function passed in compute() of Properties returns null as a return value then the mapping is removed from Properties(or remains absent if initiall
2 min read
Properties keySet() method in Java with Examples
The keySet() method of Properties class is used to create a set out of the key elements contained in the Properties. It basically returns a set view of the keys or we can create a new set and store the key elements in them. Syntax: public Set keySet() Parameters: This method accepts no parameters Returns: This method returns a Set view of the keys
2 min read
Properties keys() method in Java with Examples
The keys() method of Properties class is used to get the enumeration of the keys in this Properties object. This enumeration can be used to traverse and iterate the keys sequentially. Syntax: public Enumeration keys() Parameters: This method accepts no parameters Returns: This method returns an Enumeration of the keys of this Properties object sequ
2 min read
Properties contains(value) method in Java with Examples
The contains(value) method of Properties class is used to check if this Properties object contains any mapping of this value for any key present in it. It takes this value to be compared as a parameter and returns a boolean value as a result. This method is more expensive than the containsKey() method. Also, this method is the same in working as th
2 min read
Properties containsKey(value) method in Java with Examples
The containsKey(value) method of Properties class is used to check if this Properties object contains any mapping of this Key for any key present in it. It takes this value to be compared as parameter and returns a boolean value as result. Syntax: public Object containsKey(Object value) Parameters: This method accepts a parameter value which is the
2 min read
Properties containsValue(value) method in Java with Examples
The containsValue(value) method of Properties class is used to check if this Properties object contains any mapping of this Value. It takes this value to be compared as parameter and returns a boolean value as result. Syntax: public Object containsValue(Object value) Parameters: This method accepts a parameter value which is the value to be searche
2 min read
Properties forEach(BiConsumer) method in Java with Examples
The forEach(BiConsumer) method of Properties class perform the BiConsumer operation on each entry of hashtable until all entries have been processed or the action throws an exception. The BiConsumer operation is a function operation of key-value pair of hashtable performed in the order of iteration. Method traverses each element of Hashtable until
2 min read
Properties entrySet() method in Java with Examples
The entrySet() method of Properties class is used to get the Set view of this Properties mappings. Syntax: public Set&lt;Map.Entry&gt; entrySet() Parameters: This method do not accepts any parameters. Returns: This method returns a Set view of the mappings of this Properties object. Below programs illustrate the entrySet() method: Program 1: // Jav
2 min read
Properties elements() method in Java with Examples
The elements() method of Properties class is used to get the enumeration of this Properties object. It can be further used to retrieve the elements sequentially using this Enumeration received. Syntax: public Enumeration elements() Parameters: This method do not accepts any parameters.Returns: This method returns an Enumeration of the values in thi
2 min read
Properties equals(value) method in Java with Examples
The equals(value) method of Properties class is used to check for equality between two properties. It verifies whether the elements of one properties object passed as a parameter is equal to the elements of this properties or not. Syntax: public boolean equals(Object value) Parameters: This method accepts a parameter value of this Properties type a
2 min read
Properties getProperty(key, defaultValue) method in Java with Examples
The getProperty(key, defaultValue) method of Properties class is used to get the value mapped to this key, passed as the parameter, in this Properties object. This method will fetch the corresponding value to this key, if present, and return it. If there is no such mapping, then it returns the defaultValue. Syntax: public String getProperty(String
2 min read
Properties isEmpty() method in Java with Examples
The isEmpty() method of Properties class is used to check if this Properties object is empty or not. Syntax: public boolean isEmpty() Parameters: This method accepts no parameters Returns: This method returns a boolean value stating if this Properties object is empty or not. Below programs show the implementation of int isEmpty() method. Program 1:
2 min read
Properties list(PrintStream) method in Java with Examples
The list(PrintStream) method of Properties class is used to print this Properties list out to the specified output stream, passed as the parameter. This method can be used for debugging purpose as it can help to see the Properties elements on the stream.0 Syntax: public void list(PrintStream out) Parameters: This method accepts a parameters PrintSt
2 min read
Properties getProperty(key) method in Java with Examples
The getProperty(key) method of Properties class is used to get the value mapped to this key, passed as the parameter, in this Properties object. This method will fetch the corresponding value to this key, if present, and return it. If there is no such mapping, then it returns null. Syntax: public Object getProperty(String key) Parameters: This meth
2 min read
Properties hashCode() method in Java with Examples
The hashCode() method of Properties class is used to generate a hashCode for the given Properties containing key and values. Syntax: public int hashCode() Parameters: This method has no argument. Returns: This method returns the hashCode value for the given map. Below programs show the implementation of int hashCode() method. Program 1: // Java cod
1 min read
Properties get(key) method in Java with Examples
The get(key) method of Properties class is used to get the value mapped to this key, passed as the parameter, in this Properties object. This method will fetch the corresponding value to this key, if present, and return it. If there is no such mapping, then it returns null. Syntax: public Object get(Object key) Parameters: This method accepts a par
2 min read
Properties getOrDefault(key, defaultValue) method in Java with Examples
The getOrDefault(key, defaultValue) method of Properties class is used to get the value mapped to this key, passed as the parameter, in this Properties object. This method will fetch the corresponding value to this key, if present, and return it. If there is no such mapping, then it returns the defaultValue. Syntax: public Object getOrDefault(Objec
2 min read
Properties list(PrintWriter) method in Java with Examples
The list(PrintWriter) method of Properties class is used to print this Properties list out to the specified output stream, passed as the parameter. This method can be used for debugging purpose as it can help to see the Properties elements on the stream.0 Syntax: public void list(PrintWriter out) Parameters: This method accepts a parameters PrintWr
2 min read
Difference between YAML(.yml) and .properties file in Java SpringBoot
These are the files to have different configurations properties required to make the application up and run like to connect with the database what are the credentials, on which port the application will run, etc. YAML (.yml) File: YAML is a configuration language. Languages like Python, Ruby, Java heavily use it for configuring the various properti
3 min read
Reading and Writing Properties File in Java
The property file is a file we use in the Java Programming language to keep the configuration parameters. These files we called Resource Bundle because it is a bundle of resources that we are going to use in the application. What are the configuration parameters? Configuration parameters are the parameters that you use at the time of configuring yo
4 min read
How to Create and Modify Properties File Form Java Program in Text and XML Format?
Properties file are a text-oriented key value a pair of contents present in a Java project with .properties extension. Line by line, the key-value pair of contents are present, and they are usually prepared by means of notepad, Wordpad, EditPlus, etc., Properties files are usually helpful to store important sensitive information and in this article
5 min read
Properties of Constructors in Java
A constructors in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling the
3 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java.util.TimeZone Class (Set-2) | Example On TimeZone Class
TimeZone class (the methods of this class was discussed in this article Java.util.TimeZone Class | Set 1) can be used in many cases like using TimeZone class we can get the time difference in term of hour and minute between two places.Problem : How we can get time difference of time in terms of hours and minutes between two places of Earth?Solution
5 min read