Question: I once saw a talk by Douglas Crockford where, in the context of javascript, he mentioned that it could be useful to store secrets in closures.

I imagine this could be naively implemented like this in Java:

```
public static Supplier<String> passwordStore(String encryptedPassword){
    String plainTextPassword = encryptedPassword; //do some decryption
    return () -> plainTextPassword;
}

```

I wonder: Is there any benefit to doing this? Is it maybe in some way less secure?

Answer: 
No reason to do that. Store the password in the array of characters, since they must be explicitly converted to String if you want to print them out. 

Consider the following example:

```
String stringPassword = "password";
char[] charactersPassword = new char[]{'p','a','s','s','w','o', 'r', 'd'};

System.out.println("Password: " + stringPassword);     // Password: password
System.out.println("Password: " + charactersPassword); // Password: [C@6ce253f1

```

The main idea is you can clear the array's items, since it is not immutable (`@Klitos Kyriacou`).

```
Arrays.fill(charactersPassword, '0');

```

Moreover, if you store the password as a plain text - String, which is immutable, it will be available in the memory for a long time (which is still somehow accesible) until the Garbage collector takes care of it.

Anyway, it's highly recommended to look after some security library which can handle much more than inventing a new (usually still risky) way.
Here's a very "engineered" example so **DO NOT USE IT IN YOUR CODE**.

I think the effect can be better demonstrated with a predicate rather than a supplier.

Assume you implement a password checker as follows:

```
public class PasswordChecker {

    private final String secretPassword;

    public PasswordChecker(String secretPassword) {
        this.secretPassword = secretPassword;
    }

    public boolean test(String password) {
        return Objects.equals(this.secretPassword, password);
    }

}

```

Then you can create an instance an pass it around:

```
final PasswordChecker passwordChecker = new PasswordChecker("changeit");

```

And somewhere else you could use it to check the password:

```
assertThat(passwordChecker.test("foobar")).isFalse();

```

However for the client which has an instance of `PasswordChecker` at hand, it is not so difficult to extract the password with some reflection:

```
    Field secretPasswordField = passwordChecker.getClass().getDeclaredField("secretPassword");
    secretPasswordField.setAccessible(true);
    String secretPassword = (String) secretPasswordField.get(passwordChecker);
    System.out.print(secretPassword);

```

Now here's the same thing with a closure:

```
final String secretPassword = "changeit";
final Predicate<String> passwordChecker = password -> Objects.equals(secretPassword, password);

```

Now you can't extract `secretPassword` from the `passwordChecker`.