Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
Jun 18, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Passing Named Arguments to Java Programs

Here's an example of a better way to pass arguments to main() methods of Java classes than using String[] args. First, pass two named parameters, user and level, that come into a GamePlayer class:

java   -Duser=champ   -Dlevel=expert   GamePlayer

Classes will use them as follows:

  public class GamePlayer {
     public static void main( String[] args ) {
        String user = System.getProperty( "user", "unknown" );   // get user name or use 'unknown'

        System.out.println( "Welcome to Inter-Galactic Rooster Race: " + user ); 
        GameStarter.start(); // start game which uses the start level 

  class GameStarter { // use arguments in other classes as well
     static void start() {
        System.out.println( "Your level " + System.getProperty( "level", "beginner" ) );

The parameters are preceded by a -D, to indicate that they are named properties. The arguments will not be available in the String argument array of the main() method. With -D parameters, you do not have to worry about the positions, and can refer to the arguments by name. You can use the arguments in other methods and even other classes, without having to pass them around. A second parameter to System.getProperty() is used as a default value in case the named parameter has not been passed. You can use this code to list all passed properties, including system properties, to standard output:

    System.getProperties().list( System.out ); // get properties from system and list them to stdout
Rakesh Goenka
Thanks for your registration, follow us on our social networks to keep up-to-date