Passing arguments and properties from command line

October 9, 2007

Java

Arguments and properties can be passed to a java application from command line.
In this techical tip, let us see how to pass arguments as well as properties from command line.

Passing arguments from command line

The syntax to pass arguments from command line is as follows,

1
2
 
java <classname>  <argument1>  <argument2>  <argument3> ........

The following example shows the usage of command line arguments.

ArithmeticOperationTest.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
 
public class ArithmeticOperationTest {
 
    public static void main(String[] arguments) {
 
        if(arguments.length > 0)
        {
            float numberOne = getNumber(arguments[0]);
            float numberTwo = getNumber(arguments[1]);
            char operator = getOperator(arguments[2]);
            float result = 0.00f;
 
            if (operator == '+'){
                result = numberOne + numberTwo;
            }else if (operator == '-'){
                result = numberOne - numberTwo;
            }else if (operator == '/'){
                result = numberOne / numberTwo;
            }
 
            System.out.println("result of " +  numberOne + " " + operator
                + " " + numberTwo + " is " + result);
        }
    }
 
    static float getNumber(String number){
 
        float retNumber = 0.0f;
        retNumber = Float.parseFloat(number.trim());
        return retNumber;
    }
 
    static char getOperator(String argument){
        char retOperator = ' ';
        retOperator = argument.trim().charAt(0);
        return retOperator;
    }
}

To run the above program issue the following at command line,

1
java ArithmeticOperationTest 10 5 /

The output is,

1
result of 10.0 / 5.0 is 2.0

Now, let us see how to pass properties from command line.

Passing properties from command line

The syntax to pass properties from command line is as follows,

1
2
 
java –D<property1-name>=<property1-value> –D<property2-name>=<property2-value> ....... <class-Name>

The getProperty( ) method in System class is used to get the value of a property by specifying the property name as key.

Consider the following example,

1
2
3
4
5
6
7
8
9
10
11
12
public class ScoreCardPropertiesTest {
 
    public static void main(String[] args) {
 
        String subject = System.getProperty("subject");
        System.out.println("subject is " +subject);
        String score = System.getProperty("score");
        System.out.println("score is " +score);
        String grade = System.getProperty("grade");
        System.out.println("grade is " +grade);
    }
}

We pass properties subject, score and grade to the above ScoreCardPropertiesTest class as follows,

1
java -Dsubject=Maths -Dscore=95 -Dgrade=A ScoreCardPropertiesTest

The output is,

1
2
3
subject is Maths
score is 95
grade is A

email

Comments

comments