Command Line Arguments - top of Musings page

By: Nicholas Duchon


In this example, I have created a program that has 4 variables which are given default values that may be overridden by command line arguments. The arguments are assumed to be in order, if they appear.
// Usage - calling the program:
> java MyExample
> java MyExample 342
> java MyExample 43 Tuesday
> java MyExample 78 "When in Rome" 4.554e-12
> java MyExample 78 "Where do all these other hands come from, anyway?" 34.43 true

// File: MyExample.java
// Date: Sep 14, 2009
// Author: Nicholas Duchon
// Purpose: Demonstrate one way to handle
// optional command line arguments

public class MyExample {

public static void main (String args []) {
int w = 91;
String x = "One more time";
double y = Math.PI;
boolean z = false;

if (args.length > 0) w = Integer.parseInt (args[0]);
if (args.length > 1) x = args[1];
if (args.length > 2) y = Double.parseDouble (args[2]);
if (args.length > 3) z = Boolean.parseBoolean (args[3]);

System.out.printf ("w = %d\n" , w);
System.out.printf ("x = >%s<\n", x);
System.out.printf ("y = %g\n" , y);
System.out.printf ("z = %b\n" , z);
} // end main

} // end class MyExample

ND.