C:\>java myProgram "Input String"
When main(String[] args)
starts running,
args[0]
will refer to the string "Input String"
This program reverses the characters of its argument.
It does this by copying characters one at a time from right to left
from the input string to the end of a reversed string.
The method data.charAt(j)
returns the
character at position j
in the string data
.
public class ReverseTester { public static String reverse( String data ) { String rev = new String(); for ( int j=data.length()-1; j >= 0; j-- ) rev += data.charAt(j); return rev; } public static void main ( String[] args ) { if ( args.length > 0 ) System.out.println( reverse( args[0] ) ); } }
Here is a sample run of this program:
C:\cs151\Notes/chap49D>java ReverseTester "This is argument 0" 0 tnemugra si sihT
The string that follows the program name on the command line
is available to the program in slot zero of the array
of arguments, args
.
The main()
method calls the reverse()
method with
that string and gets back a reversed string.