Environment Variables With Getenv Defaults
Read configuration from System.getenv with explicit fallbacks, because getenv returns null for missing variables and the map itself is read-only.
Code
import java.util.Map;
public class EnvConfig {
public static void main(String[] args) {
// getenv 对缺失变量返回 null,而不是抛异常:读之前先定默认值
String region = System.getenv("DEPLOY_REGION");
String effective = region == null || region.isBlank() ? "eu-central-1" : region;
// 几乎必然存在的系统级变量
String path = System.getenv("PATH");
// 整张环境变量表是只读视图:put/remove 都会抛 UnsupportedOperationException
Map<String, String> env = System.getenv();
System.out.println("region: " + effective);
System.out.println("PATH present: " + (path != null && !path.isBlank()));
System.out.println("visible vars: " + env.size());
System.out.println("missing var: " + System.getenv("DEPLOY_NO_SUCH_VAR"));
}
}How it works
Count the class EnvConfig and the function main as the entire surface area of Environment Variables With Getenv Defaults.
Using it
The demo output is labeled (region:, PATH present:, visible vars:), so every printed line maps back to its originating operation.
Key statements
String effective = region == null || region.isBlank() ? "eu-central-1" : region;
String region = System.getenv("DEPLOY_REGION");
Map<String, String> env = System.getenv();
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- What does Environment Variables With Getenv Defaults print when run?
- The script runs standalone; its 4 labeled outputs include `region:`, `PATH present:`, `visible vars:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.