This is the typical format for declaring the main program
|
The number of Strings that are in args can be found by using the length property.
System.out.println("There are " + argc + " command line arguments:"); Note: Arrays are indexed beginning with 0, so an array that has three elements will use index [0], [1], and [2]. |
Here is a complete program that will print out a list of command line arguments, one per line:
public class echo2 { public static void main (String[] args) { String s=""; int argc = args.length; System.out.println("There are " + argc + " command line arguments:"); for (int i = 0; i< argc; i++) { System.out.println("Argument #" + i + ": " + args[i]); } } } |
There are 0 command line arguments:
There are 3 command line arguments: Argument #0: parameter1 Argument #1: parameter2 Argument #2: parameter3
There are 5 command line arguments: Argument #0: these Argument #1: are Argument #2: command Argument #3: line Argument #4: arguments
There are 1 command line arguments: Argument #0: these are command line arguments |
In some languages there is a "foreach" loop that will process all elements of a collection. In java a similar for loop can be used. In the example below a String variable s is declared and then used to process each member of the args array. This example has the same functionality as the echo2 program above.
Source: The javaTMTutorials at Oracle.com. public class echo { public static void main (String[] args) { for (String s: args) { System.out.println(s); } } } |