Java Reference
In-Depth Information
The program responds:
this is a test
In this case, the args array has a length of four. The first element in the array,
args[0] , is the string “this” and the last element of the array, args[3] , is “test”. As
you can see, Java arrays begin with element 0 . If you are coming from a language
that uses one-based arrays, this can take quite a bit of getting used to. In particu-
lar, you must remember that if the length of an array a is n , the last element in the
array is a[n-1] . You can determine the length of an array by appending .length
to its name, as shown in Example 1-4.
This example also demonstrates the use of a while loop. A while loop is a simpler
form of the for loop; it requires you to do your own initialization and update of
the loop counter variable. Most for loops can be rewritten as a while loop, but
the compact syntax of the for loop makes it the more commonly used statement.
A for loop would have been perfectly acceptable, and even preferable, in this
example.
Example 1−4: Echo.java
package com.davidflanagan.examples.basics;
/**
* This program prints out all its command-line arguments.
**/
public class Echo {
public static void main(String[] args) {
int i = 0; // Initialize the loop variable
while(i < args.length) { // Loop until the end of array
System.out.print(args[i] + " "); // Print each argument out
i++;
// Increment the loop variable
}
System.out.println();
// Terminate the line
}
}
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 com.davidflanagan.examples.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
Search WWH ::




Custom Search