Get Environment Variables and System Properties in Java

What is an Environment Variable?

An environment variable is a system variable, and any program can access it for various reasons, like locating the path of the program, user names etc., which you would like to make it accessible for all or specific program.

An environment variable often named all in CAPS, for example PATH. Each environment variable contains a value in text format.

Java Program to Read an Environment Variable

We can access Environment variables from within a Java program by using System.getenv. System is a class that is available within java.lang package. So, you don’t have to import this class. Method System.getenv accepts a String value which represents the environment variable and returns a String that contains value of that environment variable.

package com.techstackjournal;

public class ReadEnvVariables {

	public static void main(String[] args) {




What is a System Property?

System property is key and value pair passed as VM argument to the java program. While passing a system property we prefix -D to the system property key-value pair.

Java Program to Read a System Property

To read a system property, we can use System.getProperty method. We need to pass the property key name into System.getProperty method to get the value of that key.

package com.techstackjournal;

public class ReadSystemProperty {

	public static void main(String[] args) {
		String companyName = System.getProperty("company_name");




If you are running it on Eclipse,

  • right click and select “Run As” => “Run Configuration”.
  • Create new launch configuration
  • Under Arguments=>VM arguments, enter -Dcompany_name=Tech Stack Journal
  • Click on Run
See also  Substring Based on a Character in Java

To run this program from command-line:

java -D"company_name=Tech Stack Journal" com.techstackjournal.ReadSystemProperty