What is java.util.Properties, how do load and getProperty defaults work, why is extending Hashtable awkward, and what replaces it for typed configuration?
answer
- strings only, on purpose
- a line-oriented key and value file
- a second list searched on a miss
- inherited Map methods know nothing of defaults
- parse once into a record
basics
~20 sjava.util.Properties holds string key-value pairs loaded from a line-based file, with getProperty falling back to a defaults list. Inheriting from Hashtable exposes put calls accepting non-strings and get calls ignoring defaults. For typed settings, parse into an immutable record at start-up.
solid answer
~40 s`java.util.Properties` is a string-to-string list that `load` reads from a line-oriented format: `key=value`, `key: value` or `key value`, with `#` or `!` comment lines and a trailing backslash to continue a line. `load(InputStream)` assumes ISO 8859-1, so for a UTF-8 file I use `load(Reader)`. `getProperty(key)` checks this list, then its `defaults` list recursively, then returns `null`, and the two-argument form returns the argument you pass instead. Because it extends `Hashtable<Object,Object>`, it inherits `put`, which accepts non-strings that `getProperty` then treats as missing, and `get`, `size` and `keySet`, which ignore defaults. Every value is a string, so for typed configuration I parse once at start-up into an immutable record with `Integer.parseInt` or `Duration.parse`, failing fast, and pass that record around; a framework's configuration binding does the same job.
code
java · 27 linesimport java.io.IOException;
import java.io.StringReader;
import java.time.Duration;
import java.util.Properties;
public class ConfigDemo {
record ServerConfig(int port, Duration timeout) {
static ServerConfig from(Properties p) {
return new ServerConfig(
Integer.parseInt(p.getProperty("server.port", "8080")),
Duration.parse(p.getProperty("server.timeout", "PT30S")));
}
}
public static void main(String[] args) throws IOException {
Properties defaults = new Properties();
defaults.setProperty("server.port", "9090");
Properties props = new Properties(defaults);
props.load(new StringReader("server.timeout = PT5S\n"));
System.out.println(ServerConfig.from(props)); // ServerConfig[port=9090, timeout=PT5S]
System.out.println(props.getProperty("server.port")); // 9090, from the defaults
System.out.println(props.get("server.port")); // null, get ignores the defaults
}
}go deeper
Recall that Properties holds string pairs read by load from a key=value file, that getProperty can fall back to defaults, and that setProperty rather than put is the method to use.
Explain the format rules that surprise people, such as trailing spaces kept and # comments only on their own line, plus ISO 8859-1 in load(InputStream), and why get ignores defaults while getProperty does not.
Show the judgment: a Reader with a known charset, try-with-resources because load leaves the stream open, and a start-up step that parses and validates every value so a bad setting fails immediately.
Weigh a shared configuration convention: file format, precedence between files and environment, and validation at start-up. Decide whether plain Properties plus a record is enough or whether a framework's binding earns its dependency.
## What Properties is `java.util.Properties`, in the JDK since 1.0, is a persistent list of string keys and string values that can be read from and written to a stream. `System.getProperties()` returns one. It is declared as `class Properties extends Hashtable<Object,Object>`, which explains most of its rough edges. Its documentation states that it is thread-safe: multiple threads can share one object without external synchronization. ## The .properties format `load` reads a simple line-oriented format: - **Comments:** a line whose first non-whitespace character is `#` or `!`. Text after `#` on a key-value line is not a comment: `host = a.example # primary` gives the value `a.example # primary`. - **Keys:** everything up to the first unescaped `=`, `:` or whitespace, so `port=8080`, `port: 8080` and `port 8080` mean the same thing. - **Values:** all remaining characters on the line, including trailing spaces. A key alone gets the empty string. - **Continuation:** a backslash at the end of a line joins the next one, and the next line's leading whitespace is dropped. - **Escapes:** `\n`, `\t` and `\uXXXX` work as expected, and a backslash before a character with no escape meaning is silently dropped. - **Repeats:** a later line for the same key replaces the earlier one. - **Round trips lose comments.** `load` ignores comment lines, and `store` writes the entries back under a comment line of its own, by default the current date and time, so a file people maintain by hand should not be rewritten with `store`. ## Loading and encoding `load` has two overloads, and they differ in one way that matters: - `load(InputStream)` assumes **ISO 8859-1**, each byte one character, so a UTF-8 file with `Zürich` reads as `Zürich`. - `load(Reader)`, since Java 6, uses the charset of the reader you give it. `Files.newBufferedReader(path)` decodes UTF-8. Neither closes what it was given ("the specified stream remains open"), so use try-with-resources. ## Two kinds of default - **A defaults list.** `new Properties(defaults)` chains a second object. `getProperty(key)` searches this list, then the defaults and their defaults recursively, then returns `null`. Nothing is copied, and `store` does not write the defaults out. - **A default argument.** `getProperty(key, defaultValue)` runs the same search and returns the argument only if every list misses. ## Why extending Hashtable is awkward The parent puts an `Object`-keyed map API on a class meant for strings, and most of those methods know nothing about defaults: | Method | Sees `defaults`? | A non-`String` entry | |---|---|---| | `getProperty` | Yes | A non-`String` value counts as missing | | `stringPropertyNames` | Yes | Omitted | | `propertyNames` | Yes | A non-`String` key throws `ClassCastException` | | `get`, `getOrDefault`, `containsKey`, `keySet`, `size` | No | Treated like any other entry | | `store` | No | Throws `ClassCastException` | The consequences: - `put` and `putAll` accept any non-null object, and the class documentation says their use is "strongly discouraged". After `p.put("timeout", 30)`, `p.getProperty("timeout")` returns `null`, so a wrong type looks like a missing setting. - `p.get("port")` can return `null` while `p.getProperty("port")` returns a value from the defaults. - The declared type is `Hashtable<Object,Object>`, so a `Properties` object cannot be passed as a `Map<String,String>`. - Internally, values live in a private `ConcurrentHashMap` and not in the inherited table, so collection-view iterators may not fail fast, unlike `Hashtable`'s. Stick to `setProperty`, `getProperty` and `stringPropertyNames`, and treat the inherited map methods as off limits. ## What to use for typed configuration `Properties` has no typed getters: a port is the string `"8080"`. It remains a fine file reader, but the rest of the application should not see it: 1. Load the file once at start-up. 2. Parse each value with the matching method, such as `Integer.parseInt` or `Duration.parse`, naming the key in any failure. 3. Build an immutable `record` from the parsed values (Java 16 and later; a final class with final fields before that), validating ranges in its constructor. 4. Pass that record to whatever needs it. A bad value then stops the application at start-up, not at first use hours later. When a setting can also come from an environment variable or a `-D` option, decide the precedence in this same step, so there is one answer to where a value came from. An application framework's configuration binding does the same job with less code, and for locale-specific text `ResourceBundle` is the matching JDK class.
- Why does a UTF-8 .properties file show garbled text after Java's Properties.load(InputStream)?`load(InputStream)` assumes ISO 8859-1, one byte per character, so the two UTF-8 bytes of `ü` read as `ü`. Use `load(Reader)` with a UTF-8 reader, or write such characters as `\uXXXX` escapes. JEP 226 made property resource bundles default to UTF-8 in Java 9, but it changed `ResourceBundle` loading and not this method.
- What is wrong with the line path=C:\new\temp in a file read by java.util.Properties?A backslash starts an escape during loading, so `\n` becomes a newline and `\t` a tab, and the value is `C:`, a newline, `ew`, a tab and `emp`, with no error. Before a character with no escape meaning the backslash is silently dropped. Write `C:\\new\\temp`, or use forward slashes where the code reading the value accepts them.
- Is a java.util.Properties object safe to share between threads?For individual calls, yes: its documentation says multiple threads can share one object without external synchronization. Inside the JDK's implementation, not the contract, values sit in a private `ConcurrentHashMap`: simple reads take no lock and writes stay synchronized. That does not make a sequence of calls atomic, and collection-view iterators may not fail fast. Copying the settings into an immutable record at start-up avoids the question.
- Properties.get(key) checks the defaults list just as getProperty(key) does.
- Properties.load(InputStream) reads UTF-8, because that has been the default charset since Java 18.
- Text after # on a key=value line is a comment.
- Properties.load trims trailing spaces from values.
- Properties.load closes the stream it was given.
- A value stored with put as an Integer can be read back as text through getProperty.
- java.util.Properties
- Java 1.0
- Properties.load(Reader)
- Java 1.6
- Records
- Java 16pre-release 14
context
- Properties (Java SE 27 & JDK 27)docs.oracle.com
- JEP 395: Recordsopenjdk.org
- Properties.java at jdk-27-gagithub.com