Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Object Class in Java
Next article icon

Properties Class in Java

Last Updated : 24 Nov, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

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",
                      "[email protected]");
  
        // 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.


Next Article
Object Class in Java
author
kartik
Improve
Article Tags :
  • Java
  • Java - util package
  • Java-Collections
Practice Tags :
  • Java
  • Java-Collections

Similar Reads

  • Object Class in Java
    Object class in Java is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class. If a class does not extend any other class then it is a direct child class of the Java Object class and if it extends another class then it is indirectly derived. The Ob
    8 min read
  • Wrapper Classes in Java
    A Wrapper class in Java is one whose object wraps or contains primitive data types. When we create an object in a wrapper class, it contains a field, and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object. Let's check on the wr
    6 min read
  • Types of Classes in Java
    A class is a blueprint in the Java programming language from which an individual object can be built. In Java, we may declare a class by using the class keyword. Class members and functions are declared simply within the class. Classes are required for the creation of Java programs. The object-orien
    8 min read
  • String Class in Java
    A string is a sequence of characters. In Java, objects of the String class are immutable, which means they cannot be changed once created. In this article, we are going to learn about the String class in Java. Example of String Class in Java: [GFGTABS] Java // Java Program to Create a String import
    7 min read
  • Static class in Java
    Java allows a class to be defined within another class. These are called Nested Classes. Classes can be static which most developers are aware of, henceforth some classes can be made static in Java. Java supports Static Instance Variables, Static Methods, Static Block, and Static Classes. The class
    3 min read
  • Classes and Objects in Java
    In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects, wh
    12 min read
  • Triplet Class in JavaTuples
    A Triplet is a Tuple from JavaTuples library that deals with 3 elements. Since this Triplet is a generic class, it can hold any type of value in it. Since Triplet is a Tuple, hence it also has all the characteristics of JavaTuples:  They are TypesafeThey are ImmutableThey are IterableThey are Serial
    5 min read
  • Java Writer Class
    Java writer class is an abstract class in the java.io package. It is designed for writing character streams. Writer class in Java provides methods for writing characters, arrays of characters, and strings. Since it is an abstract class, we cannot create an instance of it directly. Instead, we will u
    5 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 co
    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
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences