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.
also read:
- Java Tutorials
- Java EE Tutorials
- Design Patterns Tutorials
- Java File IO Tutorials
Passing arguments from command line
The syntax to pass arguments from command line is as follows,
[code]
java <classname> <argument1> <argument2> <argument3> ……..
[/code]
The following example shows the usage of command line arguments.
ArithmeticOperationTest.java
[code lang=”java”]
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;
}
}
[/code]
To run the above program issue the following at command line,
[code lang=”java”]
java ArithmeticOperationTest 10 5 /
[/code]
The output is,
[code lang=”java”]
result of 10.0 / 5.0 is 2.0
[/code]
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,
[code lang=”java”]
java -D<property1-name>=<property1-value> -D<property2-name>=<property2-value> ……. <class-Name>
[/code]
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,
[code lang=”java”]
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);
}
}
[/code]
We pass properties subject, score and grade to the above ScoreCardPropertiesTest class as follows,
[code]
java -Dsubject=Maths -Dscore=95 -Dgrade=A ScoreCardPropertiesTest
[/code]
The output is,
[code]
subject is Maths
score is 95
grade is A
[/code]
Leave a Reply