Passing Named Arguments to Java Programs

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

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist