Environment variables in Java
There are two ways to get environment variable in Java, by using System properties or by using System.getEnv(). System properties provides only limited set of predefined environment variables like java.classpath, for retriving Java Classpath or java.username to get User Id which is used to run Java program etc but a more robust and platform independent way of getting environment variable in Java program on the other hand Sytem.getEnv() method provide access to all environment variables inside Java program but subject to introduce platform dependency if program relies on a particular environment variable. Sytem.getEnv() is overloaded method in Java API and if invoked without parameter it returns an unmodifiable String map which contains all environment variables and there values available to this Java process while System.getEnv(String name) returns value of environment variable if exists or null. In our earlier posts we have seen How to get current directory in Java and How to run shell command from Java program and in this Java tutorial we will see how to access environment variable in Java.
How to get environment variables in Java - Example
Here is a quick example on How to get environment variable in Java using System.getEnv() and System.getProperty(). Remember System.getEnv() return String map of all environment variables while System.getEnv(String name) only return value of named environment variable like JAVA_HOME will return PATH of your JDK installation directory.
Getting environment variable in Java – Things to remember
Java is platform independent language but there are many things which can make a Java program platform dependent e.g. using a native library. Since environment variables also vary from one platform to another e.g. from windows to Unix you need to be bit careful while directly accessing environment variable inside Java program. Here are few points which is worth noting :
1) Use system properties if value of environment variable is available via system property e.g. Username which is available using "user.name" system property. If you access it using environment variable directly you may need to ask for different variable as it may be different in Windows e.g. USERNAME and Unix as USER.
2) Environment variables are case sensitive in Unix while case insensitive in Windows so relying on that can again make your Java program platform dependent.
3) System.getEnv() was deprecated in release JDK 1.3 in support of using System.getProperty() but reinstated again in JDK 1.5.
That's all on how to get environment variable in Java. Though you have convenient method like System.getEnv() which can return value of environment variable, its better to use System.getProperty()to get that value in a platform independent way, if that environment variable is available as system property in Java.
Other How to tutorials from Javarevisited Blog