The Java Preferences API: Storing User Settings
Remembering window positions, recent files and options with java.util.prefs: user and system trees, nodes named like packages, typed values with defaults, size limits, change listeners, XML export and import, the platform backing stores, and plugging in your own store with PreferencesFactory.
kvi5hnuCode Sprout team member10 min readOn this page
Desktop programs are expected to remember things: where the window was, which file was open last, whether the user prefers a dark theme. You could write a properties file, but where? Each operating system has its own conventions for configuration locations, and two applications that both choose ~/.config.properties will overwrite each other. The java.util.prefs package answers both questions: it gives each application a place in a central, per-user repository and hides how and where that repository is stored.
Trees of nodes

Preferences are organized as two kinds of trees:
- a user tree for each user, for personal settings, reached with
Preferences.userRoot(); - one system tree shared by all users of the machine, reached with
Preferences.systemRoot(). Writing to it usually requires administrator rights.
Each tree consists of nodes with path names such as /com/example/viewer. As with packages, starting paths with a reversed domain name avoids collisions; the API designers suggest using exactly your package name. Get a node, creating it if needed, with node(path); absolute paths start at the root, relative ones at the current node:
Preferences app = Preferences.userRoot().node("/com/example/viewer");
Preferences window = app.node("window"); // /com/example/viewer/window
Preferences same = Preferences.userNodeForPackage(Viewer.class); // node named after the class's package
userNodeForPackage and systemNodeForPackage take a Class and return the node whose path matches its package. A class in the unnamed package maps to the node /<unnamed>. nodeExists(path) checks for a node without creating it, childrenNames() lists children, and removeNode() deletes a node with everything below it.
Reading and writing values
Every node holds its own table of key/value pairs. The getters always take a default value, which is returned when the key is missing, when the stored value cannot be converted to the requested type, or when the backing store is unavailable:
int x = window.getInt("x", 100);
double zoom = window.getDouble("zoom", 1.0);
String lastFile = app.get("lastFile", null);
There are matching put methods: put, putInt, putLong, putFloat, putDouble, putBoolean and putByteArray, plus get/getInt/... getByteArray for reading. remove(key) deletes one entry and clear() all entries of a node. keys() lists the keys.
The mandatory default is a design decision: preferences are an optimization, not a database. A missing setting must never stop the program; it simply starts with defaults on a new machine or for a new user.
Some details:
- Everything is stored as a string.
putInt("x", 240)stores"240";getIntparses it back. That is whykeys()cannot tell you a value's type, and whygetInton a non-numeric string returns the default. Byte arrays are stored as Base64 text. - No objects. You cannot store serializable objects; the designers considered serialization too fragile for settings that must survive upgrades. Store a few simple values, or JSON text if you must.
- Limits. Keys and node names may be at most 80 characters (
MAX_KEY_LENGTH,MAX_NAME_LENGTH), and string values at most 8,192 characters (MAX_VALUE_LENGTH). Longer ones causeIllegalArgumentException. Byte arrays may use about three quarters of that, because of the Base64 encoding. - Thread safety.
Preferencesmethods are thread-safe and may be called from any thread, including the EDT. Multiple JVMs may use the same store; the implementations coordinate writes.
When data reaches the disk
Writes go to an in-memory cache first and reach the backing store asynchronously: periodically and when the JVM shuts down normally. Call flush() to force pending changes out, for example before a risky operation, and sync() to also pick up changes made by other programs. Both throw BackingStoreException if the store cannot be reached.
Listening for changes
addPreferenceChangeListener reports added, changed and removed keys of one node (PreferenceChangeEvent.getKey(), getNewValue(), which is null for a removal). addNodeChangeListener reports children added or removed. Events are delivered on a background thread, not the EDT, so a listener that updates Swing components must use EventQueue.invokeLater. Changes made by other JVMs are not guaranteed to produce events.
Export and import
Central repositories such as the Windows registry tend to collect stale entries, and settings trapped in them are hard to move to a new computer. The Preferences API addresses the second problem with an XML exchange format:
app.exportSubtree(outputStream); // this node and all descendants
app.exportNode(outputStream); // this node only
Preferences.importPreferences(inputStream);
The XML file names the tree type (user or system) and contains each node's map of entries plus nested node elements; the demo shows a complete example. Import merges the file into the tree named in it. Offering "Export settings" and "Import settings" commands lets users move their configuration between machines.
Against the "dumping ground" problem, the API only offers good manners: use your own node, store little, and remove your node when the application is uninstalled or settings are reset.
Backing stores
The JDK chooses an implementation per platform:
| Platform | User tree | System tree |
|---|---|---|
| Windows | registry, HKEY_CURRENT_USER\Software\JavaSoft\Prefs | HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs |
| macOS | a property list in ~/Library/Preferences | a property list in /Library/Preferences |
| Linux and other Unix | XML files under ~/.java/.userPrefs | /etc/.java/.systemPrefs |
The location of the Unix files can be changed with the system properties java.util.prefs.userRoot and java.util.prefs.systemRoot. On Linux, an unprivileged program that touches the system tree logs warnings because it cannot create /etc/.java; stick to the user tree for per-user settings.
You can also install a completely different store: implement java.util.prefs.PreferencesFactory, usually with node classes extending AbstractPreferences (which handles caching, events, validation and export, leaving a handful of ...Spi methods), and select it with the system property java.util.prefs.PreferencesFactory or a META-INF/services entry. The demo uses this to keep everything in memory, so it never touches your real settings. The same technique isolates unit tests.
A program that remembers
This frame restores its bounds and the last opened file on startup, saves its bounds when closed, and offers export and import of its settings:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.prefs.*;
import javax.swing.*;
public class RememberingFrame {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
Preferences prefs = Preferences.userRoot().node("/com/example/rememberingframe");
var frame = new JFrame("I remember where I was");
// Restore the last bounds, with sensible defaults on the first run
frame.setBounds(prefs.getInt("x", 100), prefs.getInt("y", 100),
prefs.getInt("width", 480), prefs.getInt("height", 320));
var label = new JLabel("Last file: " + prefs.get("lastFile", "(none)"), SwingConstants.CENTER);
frame.add(label);
var fileMenu = new JMenu("File");
var open = new JMenuItem("Open...");
open.addActionListener(_ -> {
var chooser = new JFileChooser(prefs.get("lastDir", null));
if (chooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
File f = chooser.getSelectedFile();
prefs.put("lastFile", f.getPath());
prefs.put("lastDir", f.getParent());
label.setText("Last file: " + f.getPath());
}
});
var export = new JMenuItem("Export Preferences...");
export.addActionListener(_ -> {
var chooser = new JFileChooser();
if (chooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
try (var out = new FileOutputStream(chooser.getSelectedFile())) {
prefs.exportSubtree(out);
} catch (IOException | BackingStoreException e) {
JOptionPane.showMessageDialog(frame, e);
}
}
});
var importItem = new JMenuItem("Import Preferences...");
importItem.addActionListener(_ -> {
var chooser = new JFileChooser();
if (chooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
try (var in = new FileInputStream(chooser.getSelectedFile())) {
Preferences.importPreferences(in);
} catch (IOException | InvalidPreferencesFormatException e) {
JOptionPane.showMessageDialog(frame, e);
}
}
});
fileMenu.add(open);
fileMenu.add(export);
fileMenu.add(importItem);
var menuBar = new JMenuBar();
menuBar.add(fileMenu);
frame.setJMenuBar(menuBar);
// Save the bounds when the window closes
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
@Override public void windowClosing(WindowEvent e) {
Rectangle r = frame.getBounds();
prefs.putInt("x", r.x);
prefs.putInt("y", r.y);
prefs.putInt("width", r.width);
prefs.putInt("height", r.height);
}
});
frame.setVisible(true);
});
}
}
A real application should also check that restored bounds are still on a visible screen, since the user may have disconnected a monitor; GraphicsEnvironment.getMaximumWindowBounds() or the screen devices' bounds tell you what is visible.
The program
The demo first installs an in-memory PreferencesFactory (a small AbstractPreferences subclass), then works with nodes and typed values, shows what happens with a non-numeric value and an over-long key, receives change events through a queue (they arrive on another thread), exports the tree as XML, removes it, and imports it again.
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.*;
import java.util.prefs.*;
public class Solution {
/** An in-memory preferences store, so this demo never touches the real registry or files. */
static class MemoryPreferences extends AbstractPreferences {
private final Map<String, String> values = new TreeMap<>();
MemoryPreferences(MemoryPreferences parent, String name) {
super(parent, name);
newNode = true; // tells listeners this node is new
}
@Override protected void putSpi(String key, String value) { values.put(key, value); }
@Override protected String getSpi(String key) { return values.get(key); }
@Override protected void removeSpi(String key) { values.remove(key); }
@Override protected void removeNodeSpi() { values.clear(); }
@Override protected String[] keysSpi() { return values.keySet().toArray(String[]::new); }
@Override protected String[] childrenNamesSpi() { return new String[0]; } // children are cached by the superclass
@Override protected AbstractPreferences childSpi(String name) { return new MemoryPreferences(this, name); }
@Override protected void syncSpi() {}
@Override protected void flushSpi() {}
}
/** Selected with the system property java.util.prefs.PreferencesFactory. */
public static class MemoryPreferencesFactory implements PreferencesFactory {
private static final Preferences USER = new MemoryPreferences(null, "");
private static final Preferences SYSTEM = new MemoryPreferences(null, "");
public MemoryPreferencesFactory() {}
@Override public Preferences userRoot() { return USER; }
@Override public Preferences systemRoot() { return SYSTEM; }
}
public static void main(String[] args) throws Exception {
System.setProperty("java.util.prefs.PreferencesFactory", MemoryPreferencesFactory.class.getName());
System.out.println("== Nodes ==");
Preferences root = Preferences.userRoot();
Preferences app = root.node("/com/example/viewer");
System.out.println("absolute path: " + app.absolutePath() + ", name: " + app.name() + ", user node: " + app.isUserNode());
System.out.println("relative node: " + app.node("window").absolutePath());
System.out.println("node for this class's package: " + Preferences.userNodeForPackage(Solution.class).absolutePath());
System.out.println("nodeExists(/com/example/viewer/window): " + root.nodeExists("/com/example/viewer/window")
+ ", nodeExists(/org/other): " + root.nodeExists("/org/other"));
System.out.println("\n== Typed values with defaults ==");
Preferences window = app.node("window");
System.out.println("first run, x = " + window.getInt("x", 100) + " (default)");
window.putInt("x", 240);
window.putInt("y", 180);
window.putDouble("zoom", 1.25);
window.putBoolean("maximized", false);
app.put("lastFile", "/home/user/pictures/sunset.png");
app.putByteArray("thumbnail", new byte[] {(byte) 0x89, 'P', 'N', 'G'});
System.out.println("x = " + window.getInt("x", 100) + ", zoom = " + window.getDouble("zoom", 1.0)
+ ", maximized = " + window.getBoolean("maximized", true));
System.out.println("thumbnail bytes: " + Arrays.toString(app.getByteArray("thumbnail", null))
+ ", stored as text: " + app.get("thumbnail", ""));
System.out.println("everything is a string underneath: get(\"x\") = \"" + window.get("x", "") + "\"");
app.put("theme", "dark");
System.out.println("getInt on a non-number returns the default: " + app.getInt("theme", -1));
System.out.println("keys of window: " + Arrays.toString(window.keys()) + ", children of app: " + Arrays.toString(app.childrenNames()));
System.out.println("\n== Limits ==");
System.out.println("MAX_KEY_LENGTH " + Preferences.MAX_KEY_LENGTH + ", MAX_NAME_LENGTH " + Preferences.MAX_NAME_LENGTH
+ ", MAX_VALUE_LENGTH " + Preferences.MAX_VALUE_LENGTH);
try {
app.put("k".repeat(81), "v");
} catch (IllegalArgumentException e) {
System.out.println("81-character key: " + e.getClass().getSimpleName() + " (" + e.getMessage().substring(0, 13) + ")");
}
System.out.println("\n== Change listeners (delivered on a background thread) ==");
var events = new LinkedBlockingQueue<String>();
window.addPreferenceChangeListener(e -> events.add("changed " + e.getKey() + " -> " + e.getNewValue()));
app.addNodeChangeListener(new NodeChangeListener() {
@Override public void childAdded(NodeChangeEvent e) { events.add("child added: " + e.getChild().name()); }
@Override public void childRemoved(NodeChangeEvent e) { events.add("child removed: " + e.getChild().name()); }
});
window.putInt("x", 300);
window.remove("maximized");
app.node("recent");
for (int i = 0; i < 3; i++) System.out.println(events.poll(5, TimeUnit.SECONDS));
System.out.println("\n== Export to XML ==");
var out = new ByteArrayOutputStream();
app.exportSubtree(out);
String xml = out.toString(StandardCharsets.UTF_8);
System.out.print(xml);
System.out.println("\n== Remove the tree, then import it back ==");
app.removeNode();
System.out.println("after removeNode, exists: " + root.nodeExists("/com/example/viewer"));
try {
app.get("lastFile", null);
} catch (IllegalStateException e) {
System.out.println("using the removed node: IllegalStateException: " + e.getMessage());
}
Preferences.importPreferences(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
Preferences restored = root.node("/com/example/viewer");
System.out.println("restored lastFile = " + restored.get("lastFile", "?") + ", window x = "
+ restored.node("window").getInt("x", 0) + ", recent exists: " + restored.nodeExists("recent"));
restored.flush(); // write to the backing store (a no-op here)
}
}
== Nodes ==
absolute path: /com/example/viewer, name: viewer, user node: true
relative node: /com/example/viewer/window
node for this class's package: /<unnamed>
nodeExists(/com/example/viewer/window): true, nodeExists(/org/other): false
== Typed values with defaults ==
first run, x = 100 (default)
x = 240, zoom = 1.25, maximized = false
thumbnail bytes: [-119, 80, 78, 71], stored as text: iVBORw==
everything is a string underneath: get("x") = "240"
getInt on a non-number returns the default: -1
keys of window: [maximized, x, y, zoom], children of app: [window]
== Limits ==
MAX_KEY_LENGTH 80, MAX_NAME_LENGTH 80, MAX_VALUE_LENGTH 8192
81-character key: IllegalArgumentException (Key too long:)
== Change listeners (delivered on a background thread) ==
changed x -> 300
changed maximized -> null
child added: recent
== Export to XML ==
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE preferences SYSTEM "http://java.sun.com/dtd/preferences.dtd">
<preferences EXTERNAL_XML_VERSION="1.0">
<root type="user">
<map/>
<node name="com">
<map/>
<node name="example">
<map/>
<node name="viewer">
<map>
<entry key="lastFile" value="/home/user/pictures/sunset.png"/>
<entry key="theme" value="dark"/>
<entry key="thumbnail" value="iVBORw=="/>
</map>
<node name="recent">
<map/>
</node>
<node name="window">
<map>
<entry key="x" value="300"/>
<entry key="y" value="180"/>
<entry key="zoom" value="1.25"/>
</map>
</node>
</node>
</node>
</node>
</root>
</preferences>
== Remove the tree, then import it back ==
after removeNode, exists: false
using the removed node: IllegalStateException: Node has been removed.
restored lastFile = /home/user/pictures/sunset.png, window x = 300, recent exists: true
Points to notice:
- The byte array
{0x89, 'P', 'N', 'G'}is stored as the Base64 stringiVBORw==, andget("x")returns the string"240": all values are text underneath. - A removed node object becomes unusable (
IllegalStateException); after the import, ask the root for the node again. - The XML lists every ancestor node (
com,example) with an empty map, so importing recreates the full path.
Common questions
Where are my preferences actually stored?
On Windows in the registry under HKEY_CURRENT_USER\Software\JavaSoft\Prefs; on macOS in ~/Library/Preferences/com.apple.java.util.prefs.plist; on Linux and other Unix systems in ~/.java/.userPrefs. Node names are encoded, so inspect them with the API (exportSubtree) rather than by hand.
Can I store passwords or tokens in Preferences? No. The stores are not encrypted and are readable by other programs of the same user. Use the operating system's credential store (Windows Credential Manager, macOS Keychain, the Linux Secret Service) through a library, or keep them out of the client entirely.
Why are my values not saved when the program is killed?
Writes are flushed asynchronously and at normal JVM shutdown. A kill -9, crash or power loss can lose recent changes. Call flush() after important updates.
What are the size limits?
Keys up to 80 characters, values up to 8,192 characters (Preferences.MAX_KEY_LENGTH, MAX_VALUE_LENGTH), node names up to 80 characters. Longer input throws IllegalArgumentException. Byte arrays are stored as Base64, so their limit is about three quarters of the value length.
How do I test code that uses Preferences without touching real settings?
Install an in-memory PreferencesFactory with -Djava.util.prefs.PreferencesFactory=..., as the demo does, or use a dedicated test node that you remove in teardown.
API reference
| Class / method | Purpose |
|---|---|
Preferences.userRoot(), systemRoot() | Roots of the user and system trees. |
userNodeForPackage(Class), systemNodeForPackage(Class) | Node named after a package. |
node(path), nodeExists(path), childrenNames(), parent(), removeNode() | Navigate and manage nodes. |
absolutePath(), name(), isUserNode() | Node information. |
get, getInt, getLong, getFloat, getDouble, getBoolean, getByteArray (key, default) | Read values. |
put, putInt, putLong, putFloat, putDouble, putBoolean, putByteArray | Write values. |
keys(), remove(key), clear() | Inspect and delete entries. |
flush(), sync() | Write pending changes; reload from the store. |
addPreferenceChangeListener, addNodeChangeListener | Observe changes (on a background thread). |
exportNode(out), exportSubtree(out), Preferences.importPreferences(in) | XML exchange. |
MAX_KEY_LENGTH, MAX_NAME_LENGTH, MAX_VALUE_LENGTH | 80, 80, 8192. |
PreferencesFactory, AbstractPreferences | Custom backing stores. |
Summary
java.util.prefsstores settings in a per-user tree (and a shared system tree) of nodes named like packages, in a platform-appropriate backing store.- Read with typed getters that always take a default; write with typed
putmethods. Values are strings underneath; keys and names are limited to 80 characters, values to 8,192. - Changes are cached and flushed asynchronously;
flush()forces them out. Listeners run on a background thread. exportSubtreeandimportPreferencesmove settings between machines as XML.- Plug in another store with a
PreferencesFactory, useful for tests. Use preferences for small UI state; use files in the platform's configuration directory for larger configuration.
Practice Questions
1. Why does every Preferences getter require a default value?
Preferences are optional by design. The key may never have been written (first run, new user, new machine), the stored text may not parse as the requested type, or the backing store may be unavailable. In all those cases the getter returns the default instead of throwing, so the program keeps working with reasonable settings.
2. Your program stores a 10,000-character JSON string with put and gets IllegalArgumentException. What are your options?
String values are limited to Preferences.MAX_VALUE_LENGTH, 8,192 characters. You can split the data across several keys or child nodes, compress it into a byte array (also limited by the Base64-encoded length), or, better, recognize that this is configuration data rather than a preference and store it in a file in the platform's configuration directory, keeping only its path in preferences.
3. A PreferenceChangeListener updates a JLabel and the UI sometimes shows glitches. What is wrong?
Preference change events are delivered on a separate dispatcher thread, not on the event dispatch thread. Modifying Swing components from that thread violates Swing's single-thread rule. Wrap the update in EventQueue.invokeLater(() -> label.setText(...)).
4. A program saves the window bounds in windowClosing and then calls System.exit(0) right away. Will the values be saved?
Usually yes, because the default implementations flush pending changes in a shutdown hook during a normal exit. But they are not written if the JVM is killed or halted with Runtime.halt, and flushing errors are silent. To be sure, call prefs.flush() after storing the values and handle BackingStoreException.
5. How would you write unit tests for code that uses Preferences without changing the developer's real settings?
Install a different store. Implement a PreferencesFactory whose roots are in-memory AbstractPreferences subclasses (as the demo does) and select it with the system property java.util.prefs.PreferencesFactory before the Preferences class is first used, for example in the test JVM arguments. Alternatively, design the code to receive a Preferences node as a parameter, and pass the tests a node under a unique test path that they remove afterwards.
Previous: Mouse Events and the AWT Event Hierarchy in Java
Next: Swing Layout Managers and MVC: FlowLayout, BorderLayout and GridLayout
Related reading

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.