Now that you have a better understanding of arrays the main() method’s String array will make much more sense. This section explains the purpose and use of the main() method’s String array.
The purpose of the main() method’s String array is to enable Java applications to accept and act upon command-line arguments. The javac compiler is an example of a program that takes command-line arguments, the most important of which is the name of the file to compile. The previous chapter also gave several examples of accepting program input via the command line. Now that you are armed with a better understanding of how arrays work you now have the knowledge to write programs that accept and process command-line arguments.
Example 8.13 gives a short program that accepts a line of text as a command-line argument and displays it in lower or upper case depending on the first command-line argument. Figure 8.25 shows the results of running this program.
Example 8.13: CommandLine.java
1 public class CommandLine { 2 public static void main(String[] args){ 3 StringBuffer sb = null; 4 boolean upper_case = false; 5 6 /********** check for upper case option **************/ 7 if(args.length > 0){ 8 switch(args[0].charAt(0)){ 9 case '-' : switch(args[0].charAt(1)){ 10 case 'U' : 11 case 'u' : upper_case = true; 12 break; 13 default: upper_case = false; 14 } 15 break; 16 default: upper_case = false; 17 18 }// end outer switch 19 20 sb = new StringBuffer(); //create StringBuffer object 21 22 /******* process text string **********************/ 23 if(upper_case){ 24 for(int i = 1; i < args.length; i++){ 25 sb.append(args[i] + " "); 26 }//end for 27 System.out.println(sb.toString().toUpperCase()); 28 }else { 29 for(int i = 0; i < args.length; i++){ 30 sb.append(args[i] + " "); 31 }//end for 32 System.out.println(sb.toString().toLowerCase()); 33 }//end if/else 34 35 } else { System.out.println("Usage: CommandLine [-U | -u] Text string");} 36 37 }//end main 38 }//end class
Figure 8-25: Results of Running Example 8.13