# java.util.prefs

***

**1. Store User Preferences for an Application**

```java
import java.util.prefs.Preferences;

public class UserPreferences {

    private static final String NODE_NAME = "myapp.preferences";

    public static void main(String[] args) {
        Preferences prefs = Preferences.userRoot().node(NODE_NAME);
        prefs.put("username", "john");
        prefs.putInt("age", 30);
        // Retrieve the saved preferences later
        String username = prefs.get("username", null);
        int age = prefs.getInt("age", -1);
    }
}
```

**2. Create a Node for Storing Hierarchical Preferences**

```java
import java.util.prefs.Preferences;

public class NodePreferences {

    public static void main(String[] args) {
        Preferences prefs = Preferences.userRoot().node("com/example/myapp");
        prefs.put("database.host", "localhost");
        prefs.put("database.port", "3306");
        // Traverse the node to access subnodes
        Preferences dbPrefs = prefs.node("database");
        String host = dbPrefs.get("host", null);
    }
}
```

**3. Synchronize Preferences Changes Across Multiple Applications**

```java
import java.util.prefs.Preferences;
import java.util.prefs.PreferencesFactory;

public class SyncPreferences {

    public static void main(String[] args) {
        Preferences prefs1 = Preferences.systemRoot();
        Preferences prefs2 = Preferences.systemRoot();
        // Enable synchronization for both preferences objects
        prefs1.sync();
        prefs2.sync();
        // Changes made to one preferences object will be reflected in the other
        prefs1.put("mykey", "myvalue");
        String value = prefs2.get("mykey", null);
    }
}
```

**4. Use a Custom Preferences Factory**

```java
import java.util.Map;
import java.util.prefs.AbstractPreferences;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import java.util.prefs.PreferencesFactory;

public class MyPreferencesFactory implements PreferencesFactory {

    @Override
    public Preferences userRoot() {
        return new MyPreferences();
    }

    @Override
    public Preferences systemRoot() {
        return new MyPreferences();
    }

    private static class MyPreferences extends AbstractPreferences {

        private Map<String, String> prefsData;

        @Override
        protected void putSpi(String key, String value) {
            prefsData.put(key, value);
        }

        @Override
        protected String getSpi(String key) {
            return prefsData.getOrDefault(key, null);
        }

        @Override
        protected void removeSpi(String key) {
            prefsData.remove(key);
        }

        @Override
        protected void removeNodeSpi() throws BackingStoreException {
            // Remove the entire node and all its children
            prefsData.clear();
        }

        @Override
        protected String[] keysSpi() throws BackingStoreException {
            return prefsData.keySet().toArray(new String[0]);
        }

        @Override
        protected String[] childrenNamesSpi() throws BackingStoreException {
            // Not supported in this implementation
            throw new UnsupportedOperationException();
        }

        @Override
        protected AbstractPreferences childSpi(String name) {
            // Not supported in this implementation
            throw new UnsupportedOperationException();
        }

        @Override
        protected void syncSpi() throws BackingStoreException {
            // Not supported in this implementation
        }

        @Override
        protected void flushSpi() throws BackingStoreException {
            // Not supported in this implementation
        }
    }
}
```

**5. Listen for Changes to Preferences**

```java
import java.util.prefs.Preferences;
import java.util.prefs.PreferenceChangeListener;

public class PreferenceListener {

    public static void main(String[] args) {
        Preferences prefs = Preferences.userRoot().node("myapp.preferences");
        prefs.addPreferenceChangeListener(new PreferenceChangeListener() {
            @Override
            public void preferenceChange(PreferencesChangeEvent evt) {
                System.out.println("Preference changed: " + evt.getKey());
            }
        });
        // Trigger a preference change by setting a new value
        prefs.put("mykey", "myvalue");
    }
}
```

**6. Store a Complex Data Structure in Preferences**

```java
import java.util.prefs.Preferences;
import java.util.Properties;

public class ComplexPreferences {

    public static void main(String[] args) {
        Preferences prefs = Preferences.userRoot().node("myapp.preferences");
        Properties props = new Properties();
        props.setProperty("prop1", "value1");
        props.setProperty("prop2", "value2");
        prefs.put("myproperties", props.toString());
        // Retrieve the complex data structure later
        String propsStr = prefs.get("myproperties", null);
        Properties restoredProps = new Properties();
        restoredProps.load(new StringReader(propsStr));
    }
}
```

**7. Import and Export Preferences to and from a File**

```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.prefs.Preferences;
import java.util.prefs.PreferencesFactory;

public class ImportExportPreferences {

    public static void main(String[] args) throws IOException {
        // Export preferences to a file
        Preferences prefs = Preferences.userRoot().node("myapp.preferences");
        File exportFile = new File("myprefs.xml");
        FileOutputStream out = new FileOutputStream(exportFile);
        prefs.exportSubtree(out);
        out.close();

        // Import preferences from a file
        PreferencesFactory factory = new PreferencesFactory() {
            @Override
            public Preferences systemRoot() {
                return null;
            }

            @Override
            public Preferences userRoot() {
                return null;
            }
        };
        FileInputStream in = new FileInputStream(exportFile);
        Preferences newPrefs = factory.userRoot();
        newPrefs.importPreferences(in);
        in.close();
    }
}
```

**8. Use Preferences to Store a URL**

```java
import java.net.URL;
import java.util.prefs.Preferences;

public class URLPreferences {

    public static void main(String[] args) throws Exception {
        Preferences prefs = Preferences.userRoot().node("myapp.preferences");
        URL url = new URL("https://www.example.com");
        prefs.put("myurl", url.toString());
        // Retrieve the URL later
        String urlStr = prefs.get("myurl", null);
        URL restoredUrl = new URL(urlStr);
    }
}
```

**9. Store a Boolean Value in Preferences**

```java
import java.util.prefs.Preferences;

public class BooleanPreferences {

    public static void main(String[] args) {
        Preferences prefs = Preferences.userRoot().node("myapp.preferences");
        prefs.putBoolean("myboolean", true);
        // Retrieve the boolean value later
        boolean myboolean = prefs.getBoolean("myboolean", false);
    }
}
```

**10. Store an Integer Value in Preferences**

```java
import java.util.prefs.Preferences;

public class IntegerPreferences {

    public static void main(String[] args) {
        Preferences prefs = Preferences.userRoot().node("myapp.preferences");
        prefs.putInt("myinteger", 123);
        // Retrieve the integer value later
        int myinteger = prefs.getInt("myinteger", -1);
    }
}
```

**11. Store a Double Value in Preferences**

```java
import java.util.prefs.Preferences;

public class DoublePreferences {

    public static void main(String[] args) {
        Preferences prefs = Preferences.userRoot().node("myapp.preferences");
        prefs.putDouble("mydouble", 123.45);
        // Retrieve the double value later
        double mydouble = prefs.getDouble("mydouble", -1.0);
    }
}
```

**12. Store a Float Value in Preferences**

```java
import java.util.prefs.Preferences;

public class FloatPreferences {

    public static void main(String[] args) {
        Preferences prefs = Preferences.userRoot().node("myapp.preferences");
        prefs.putFloat("myfloat", 123.45f);
        // Retrieve the float value later
        float myfloat = prefs.getFloat("myfloat", -1.0f);

```
