Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

Getting Environment Variables

Problem

You want to get at environment variables from within your Java program.

Solution

Don’t.

Discussion

The seventh edition of Unix, released in 1979, had an exciting new feature known as environment variables. Environment variables are in all modern Unix systems and in most later command-line systems such as the DOS subsystem underlying MS-Windows, but are not in Macintosh computers, Palm Pilots, SmartCards, or other Java environments. Environment variables are commonly used for customizing an individual computer user’s runtime environment, hence the name. To take one example that will be familiar to most readers, on Unix or DOS the environment variable PATH determines where the system will look for executable programs. So of course the issue comes up: “How do I get at environment variables from my Java program?”

The answer is that you can do this in some versions of Java, but you shouldn’t. Java is designed to be a portable runtime environment. As such, you should not depend on operating system features that don’t exist on every single Java platform. I just mentioned several Java platforms that don’t have environment variables.

Oh, all right, if you insist. There is a static method called getenv( ) in class java.lang.System . Let’s try it out. But remember, you made me do it. First, the code. All we need is this line in a main program:

System.out.println("System.getenv(\"PATH\") = " + System.getenv("PATH"));

Let’s try compiling it:

C:\javasrc>javac ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata