Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java setting system property using command line

While reading java man page, I found the -Dproperty=value flag which stats that by passing this flag, it will create a system property with value = value. I wrote a test java code:

class File{
    public static void main(String[] args){
        System.out.println("HOLA");
        System.out.println(System.getProperty("blah"));
    }
}

I compiled the same with javac File.java and then ran with with command java File -Dblah=blah but I got the following output

HOLA
null

and then I ran with as java -Dblah=blah File and then I got the expected output:

HOLA
blah

The question is: Is this a bug or is this an intentional behavior. It does seem a bug because in most of the program, order doesn't matter at command line.

like image 572
Dheerendra Avatar asked Jul 03 '15 16:07

Dheerendra


People also ask

How to set system property in Java?

Set System Property. In java, you can set a custom system property either from command tools or from java code itself. Set system property from code using System.setProperty() methodSystem.setProperty("custom_key", "custom_value"); That’s all for this basic tutorial for reading and writing system properties in java.

How to set the value of a system property from the command line?

Setting the Value of a System Property from the Command Line: add -D option to the java command when running your program.

How to set system properties with Maven?

We can set System Properties with maven in several ways, either using maven plugin or from command-line or from a file. 1. From Command line To provide System Properties to the tests from command line, you just need to configure maven surefire plugin and use -D {systemproperty}= {propertyvalue} parameter in commandline.

How to set environment variables for Java using command line?

How to set environment variables for Java using command line 1 JAVA_HOME: stores location of the JDK’s installation directory. When you install development tools, they will first... 2 PATH: stores paths of directories where the operating system will look, to launch the requested programs quickly. For... More ...


1 Answers

The -D needs to come before the class name, because anything after the class name is regarded as an argument to the Java app itself... and the Java app may choose to do anything it likes with -D, or any other JVM options.

Basically, the syntax is:

java [jvm-args] class-name [application-args]
like image 80
Jon Skeet Avatar answered Oct 29 '22 07:10

Jon Skeet