Command Line Arguments
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.
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
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.
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
The example below converts the command line arguments to floating point values.
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
Questions
- {{Who's on first?}}
- {{Who's on second?}}
- {{Who's on third?}}
Projects
More ★'s indicate higher difficulty level.
- Combined FICA Tax (Command Line Argument)
- Cubic Roots (Command Line)
- Dog Years (Command Line)
- Milky Way Stellar Density Estimate
- Quadratic Roots (Command Line)
References
- [[Java Language Specification]], Java SE 17 Edition, Gosling, et. al., 2021.
- [[Java Tutorials]]
- [[Java at TutorialsPoint]]
- Download Java at [[Amazon Corretto]], [[Azul Zulu]], [[Eclipse Temurin]] or [[Oracle JDK]]