1.5 Echo in Reverse

Example 1-5 is a lot like the Echo program of Example 1-4, except that it prints out the command-line arguments in reverse order, and it prints out the characters of each argument backwards. Thus, the Reverse program can be invoked as follows, with the following output:

% java je3.basics.Reverse this is a test tset a si siht

This program is interesting because its nested for loops count backward instead of forward. It is also interesting because it manipulates String objects by invoking methods of those objects and the syntax starts to get a little complicated. For example, consider the expression at the heart of this example:

args[i].charAt(j)

This expression first extracts the ith element of the args[ ] array. We know from the declaration of the array in the signature of the main( ) method that it is a String array; that is, it contains String objects. (Strings are not a primitive type, like integers and boolean values in Java: they are full-fledged objects.) Once you extract the ith String from the array, you invoke the charAt( ) method of that object, passing the argument j. (The . character in the expression refers to a method or a field of an object.) As you can surmise from the name (and verify, if you want, in a reference manual), this method extracts the specified character from the String object. Thus, this expression extracts the jth character from the ith command-line argument. Armed with this understanding, you should be able to make sense of the rest of Example 1-5.

Example 1-5. Reverse.java
package je3.basics; /**  * This program echos the command-line arguments backwards.  **/ public class Reverse {     public static void main(String[  ] args) {         // Loop backwards through the array of arguments         for(int i = args.length-1; i >= 0; i--) {             // Loop backwards through the characters in each argument             for(int j=args[i].length( )-1; j>=0; j--) {                 // Print out character j of argument i.                 System.out.print(args[i].charAt(j));             }             System.out.print(" ");  // Add a space at the end of each argument.         }         System.out.println( );       // And terminate the line when we're done.     } }


Java Examples in a Nutshell
Java Examples in a Nutshell, 3rd Edition
ISBN: 0596006209
EAN: 2147483647
Year: 2003
Pages: 285

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net