Accessing an non existing environment key

In this post under DotEnv, I will show with example how to handle retrieving values of environment keys that doesn’t exist.

Below is the main class for your reference.

Main class

1  package defaultPackage;
2
3 import io.github.cdimascio.dotenv.Dotenv;
4
5 public class Example6 {
6 public static void main(String[] args) {
7 Dotenv dotenv = Dotenv.load();
8 String value = dotenv.get("Key1");
9 System.out.println("Value: " + value);
10 value = dotenv.get("Key1", "value1");
11 System.out.println("Value: " + value);
12 }
13 }

In the above main class, we are trying to retrieve value for key “Key1” which doesn’t exist.

At line 8, we are trying to retrieve value of key “Key1” in this case it will return null.

At line 10, we are again trying to retrieve value of key “Key1” but this time we are calling an overloaded version of “get” method which also takes a default
value as a parameter in addition to key.

If the key doesn’t exist, the default value is returned.

You can use whichever “get” method you prefer. Its up to you.

In this way we can handle retrieving of non existing environment keys.

Below is the output

Output

Value: null
Value: value1

Leave a comment