286

What's the difference between system properties System.getProperties() and environment variables System.getenv() in a JVM?

Bohemian
  • 365,064
  • 84
  • 522
  • 658
Praveen Sripati
  • 29,779
  • 15
  • 74
  • 108

2 Answers2

392
informatik01
  • 15,174
  • 9
  • 67
  • 100
Bohemian
  • 365,064
  • 84
  • 522
  • 658
  • 46
    Absolutely correct, Bohemian. Environment variables are an "OS thing", and properties are a "Java thing". As it happens, Java chose to expose OS variables as properties (just as Java exposes current directory and "other stuff" as properties), but they are in fact different things. – paulsm4 Aug 14 '11 at 04:29
  • @Bohemian If I set property via `java -Dpropname=value` how can i then retrieve those properties? – Marek Sebera Jul 25 '13 at 10:08
  • 9
    `System.grtProperties()` lists all properties, and those set from command line will be there, but there's no way to distinguish those from the other properties added by the system, if that's what you're asking. – Bohemian Jul 25 '13 at 10:13
  • 14
    Note that you can also set system properties with the environment variable `JAVA_TOOL_OPTIONS`. – flacs Oct 31 '14 at 15:19
  • Do we need JVM restart to read the updated env variable ? I know for restart required to read properties updated by external source. – Kanagavelu Sugumar May 25 '17 at 10:07
  • 6
    @KanagaveluSugumar Yes, you need to restart: Environment variable settings are read from the environment on start up. i.e. `System.getenv(String name)` does not dynamically read the value from the system at call time. – Bohemian May 25 '17 at 16:01
  • @paulsm4 what do you mean by "Java chose to expose OS variables as properties"? – malana Dec 11 '17 at 09:36
161

I think the difference between the two boils down to access. Environment variables are accessible by any process and Java system properties are only accessible by the process they are added to.

Also as Bohemian stated, env variables are set in the OS (however they 'can' be set through Java) and system properties are passed as command line options or set via setProperty().

Koray Tugay
  • 20,438
  • 37
  • 155
  • 276
Jake Dempsey
  • 5,896
  • 1
  • 27
  • 24
  • 7
    Finally, it's how the variables are added and the scope of the variables. – Praveen Sripati Aug 14 '11 at 12:33
  • Keep in mind that other processes can find the cmd used to launch a process, hence java system properties as well. – Christian Jun 13 '20 at 11:23
  • There is more to it. This tutorial explains in detail: https://youtu.be/vQYfOMrdgpg - Basically env vars can also have scope, e.g. set in one shell may not be visible in another. You typically cannot set them at runtime because they are on the host, however you can set them (at runtime) in JUnit 5 using extensions etc. – Andy Cribbens Mar 03 '21 at 10:09
  • This answer seems incorrect. Environment variables are scoped per process. Each process sees its own environment. – Pedro Lamarão Apr 07 '21 at 14:17