Sams Teach Yourself C in 21 Days

(singke) #1
Java Language Fundamentals 715

BD4


part of this line is a reference to Java’s error-handling mechanisms, which will be cov-
ered on Bonus Day 6. Line 10 declares a variable of type BufferedReader. I called this
variablekbbecause it will be used for keyboard input. Line 11 declares a variable of type
String, used in Java to hold text data (covered earlier today). Line 13 initializes kbso it
is ready for use. Line 14 displays a prompt on the screen. Line 15 reads a line of text
from the keyboard and stores it in s1. Finally, line 16 displays the entered text on the
screen.
There are more details of console input/output in Java, but the above techniques will
serve for the Java programs to be presented here.

Arrays ..................................................................................................................


As in C and C++, a Java array is an indexed method of storing data. Each element in an
array has the same name, and each is distinguished from the others by a numerical index.
For example, if you create an array called MyArray, and specify that it contains 100 type
intvariables, you would have MyArray[0],MyArray[1], up to MyArray[99]. An array
can hold either primitive data types or objects. There are two steps to creating an array in
Java. First, you must declare an identifier to reference the array. The syntax is
type ArrayIdentifier[];
Typeis the name of a class or a primitive data type, and ArrayIdentifieris the name of
the array. The empty brackets are what sets an array declaration apart from a regular
variable declaration. The second step creates the actual array and sets the array identifier
to reference it:
ArrayIdentifier = new type [elements];
Typeis the data type of the array and must be the same type as used in the identifier dec-
laration.Elementsis the number of elements in the array. The two steps for creating a
Java array can be combined in a single line of code:
type ArrayIdentifier = new type[elements];
If an array is a primitive data type or the Stringtype, you can start using it without any
further steps.
String Names = new String [50];
int Numbers = new int [100];
...
Names[1] = “Peter”;
Names[2] = “John”;
Numbers[1] = 2;
Numbers[2] = Numbers[1] + 5;

39 448201x-Bonus4 8/13/02 11:19 AM Page 715

Free download pdf