Pure Programmer
Blue Matrix


Cluster Map

Command Line Arguments

L1

This page is under construction. Please come back later.

When running programs from the command line we have the option of supplying additional information in the form of arguments on the command line. Command line arguments take the form of strings separated by spaces. For example the following command line program invokation has three additional arguments.

$ java ProgramClass Fred 123 Flintstone

In our programs we can access each of these arguments using the variables args[0], args[1], args[2], etc. The first command line argument is in the variable with the 0 subscript. Additional arguments are in 1, 2, 3, etc.

CmdLineArgs1.java
import org.pureprogrammer.Utils;

public class CmdLineArgs1 {

	public static void main(String[] args) {
		System.out.println("Number of arguments: " + args.length);
		System.out.println("Program Name: " + "CmdLineArgs1");
		System.out.println("Arg 1: " + args[0]);
		System.out.println("Arg 2: " + args[1]);
		System.out.println("Arg 3: " + args[2]);
		System.out.println("Arg 4: " + args[3]);
	}
}

Output
$ javac -Xlint CmdLineArgs1.java $ java -ea CmdLineArgs1 Fred Barney Wilma Betty Number of arguments: 4 Program Name: CmdLineArgs1 Arg 1: Fred Arg 2: Barney Arg 3: Wilma Arg 4: Betty $ javac -Xlint CmdLineArgs1.java $ java -ea CmdLineArgs1 Φρειδερίκος Барнеи ウィルマ 贝蒂 Number of arguments: 4 Program Name: CmdLineArgs1 Arg 1: Φρειδερίκος Arg 2: Барнеи Arg 3: ウィルマ Arg 4: 贝蒂

If we want to treat a command line argument as a number we first need to convert from the string representation passed on the command line to a numeric type. This is where conversion functions come in handy. The example below illustrates how to convert command line arguments to integers.

CmdLineArgs2.java
import org.pureprogrammer.Utils;

public class CmdLineArgs2 {

	public static void main(String[] args) {
		final int a = Utils.stoiWithDefault(args[0], 0);
		final int b = Utils.stoiWithDefault(args[1], 0);
		final int c = a + b;
		System.out.println(Utils.format("{0:d} + {1:d} = {2:d}", a, b, c));
	}
}

Output
$ javac -Xlint CmdLineArgs2.java $ java -ea CmdLineArgs2 326 805 326 + 805 = 1131

The example below converts the command line arguments to floating point values.

CmdLineArgs3.java
import org.pureprogrammer.Utils;

public class CmdLineArgs3 {

	public static void main(String[] args) {
		final double a = Utils.stodWithDefault(args[0], 0);
		final double b = Utils.stodWithDefault(args[1], 0);
		final double c = a + b;
		System.out.println(Utils.format("{0:f} + {1:f} = {2:f}", a, b, c));
	}
}

Output
$ javac -Xlint CmdLineArgs3.java $ java -ea CmdLineArgs3 3.21 7.01 3.210000 + 7.010000 = 10.220000

Questions

Projects

More ★'s indicate higher difficulty level.

References