← Back to Chapters

Properties Class

☕ Properties Class

? Quick Overview

The Properties class in Java is used to store and manage configuration data in the form of key–value pairs. It is commonly used for application settings, database configuration, and environment-specific values.

? Key Concepts

  • Part of java.util package
  • Extends Hashtable<Object, Object>
  • Stores data as String key and String value
  • Supports loading from and saving to files
  • Widely used with .properties configuration files

? Syntax / Theory

A Properties object works like a map where both keys and values are strings. It provides helper methods such as load(), store(), getProperty(), and setProperty().

? Interactive Simulator

Simulate the setProperty() method. Add keys and values to see how they are stored in the Object vs. a File.

? In Memory (Map View)

  • Empty Properties Object

? File View (.properties)

# Properties File # Generated by Simulator

? Code Example — Using Properties

? View Code Example
// Demonstrates basic usage of Java Properties class
import java.util.Properties;

public class DemoProperties {
public static void main(String[] args) {

Properties props = new Properties();

props.setProperty("username", "admin");
props.setProperty("password", "secret123");

String user = props.getProperty("username");
String pass = props.getProperty("password");

System.out.println("Username: " + user);
System.out.println("Password: " + pass);
}
}

? Live Output / Explanation

Program Output

The program prints the stored configuration values:

  • Username: admin
  • Password: secret123

This shows how setProperty() and getProperty() are used to manage application settings in memory.

? Code Example — Loading from File

? View Code Example
// Loads configuration values from a .properties file
import java.io.FileInputStream;
import java.util.Properties;

public class LoadPropertiesFile {
public static void main(String[] args) throws Exception {

Properties props = new Properties();

FileInputStream fis = new FileInputStream("config.properties");
props.load(fis);

System.out.println(props.getProperty("db.url"));
System.out.println(props.getProperty("db.user"));
}
}

✅ Tips & Best Practices

  • Always store sensitive data securely (avoid plain-text passwords)
  • Use meaningful keys like db.url or app.mode
  • Close file streams properly to avoid memory leaks
  • Use one properties file per environment (dev, test, prod)

? Try It Yourself

  • Create a config.properties file and load values from it
  • Add default values using getProperty(key, defaultValue)
  • Store properties back to a file using store()