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 i
th 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 i
th
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 j
th
character from the i
th 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. } }
Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.