Java Reference
In-Depth Information
5.5 Command Line Arguments
Another place where arrays are used is when a program (this is correct: a program
and not a method) is called with a variable number of arguments. Consider the following
program.
public class
Concat
{
public static void
main(String [] args)
{
String result=
""
;
for
(String s : args)
{
result+=s;
System. out . println ( result ) ;
}
The program examines the input to the program, which is stored in the array of strings
args
. It then concatenates all the elements of the array and prints the result. In order to
test the program, we can compile it by writing the following line at the command prompt.
javac Concat.java
This will produce the file
concat.class
, which will contain the Java binary code for the
program. We can then execute the program by writing the following line at the command
prompt.
java Concat Hi There!
The result of the program will be the message: “
HiThere!
”Notethatinorderforthe
example to work, proper environment variables need to be set so that the operating system
knows where to find the executables
java
and
javac
. Alternatively, the statements can be
executed in the directory that contains the two Java binaries. In this case, however, the
directory of the Java files must be specified.
5.6 Summary
This chapter introduced one and two-dimensional arrays. Arrays are useful for allocating
storage for more than one element of the same type in a single statement. A one-dimensional
array allocates contiguous space that is referenced using a single index. Conversely, a two-
dimensional array declares space in main memory in the form of a table that is referenced
using two indices. Later on, in Chapter 7, we will explore additional array topics, such as
arrays of objects and the
ArrayList
class.
5.7 Syntax
Declares the variable
a
to be of type array of integers. We can declare
an array of any primitive type or class.
⇒
int[] a;