Java Reference
In-Depth Information
You can read the code as “for each element u in myList , do the following.” Note that the vari-
able, u , must be declared as the same type as the elements in myList .
In general, the syntax for a for-each loop is
for (elementType element: arrayRefVar) {
// Process the element
}
You still have to use an index variable if you wish to traverse the array in a different order or
change the elements in the array.
Caution
Accessing an array out of bounds is a common programming error that throws a runtime
ArrayIndexOutOfBoundsException . To avoid it, make sure that you do not use
an index beyond arrayRefVar.length - 1 .
Programmers often mistakenly reference the first element in an array with index 1 , but it
should be 0 . This is called the off-by-one error . Another common error in a loop is using
<= where < should be used. For example, the following loop is wrong.
for ( int i = 0 ; i list.length; i++)
System.out.print(list[i] + " " );
The <= should be replaced by < .
ArrayIndexOutOfBounds-
Exception
off-by-one error
<=
6.1
How do you declare an array reference variable and how do you create an array?
Check
6.2
Point
When is the memory allocated for an array?
6.3
What is the printout of the following code?
int x = 30 ;
int [] numbers = new int [x];
x = 60 ;
System.out.println( "x is " + x);
System.out.println( "The size of numbers is " + numbers.length);
6.4
Indicate true or false for the following statements:
Every element in an array has the same type.
The array size is fixed after an array reference variable is declared.
The array size is fixed after it is created.
The elements in an array must be a primitive data type.
6.5
Which of the following statements are valid?
int i = new int ( 30 );
double d[] = new double [ 30 ];
char [] r = new char ( 1..30 );
int i[] = ( 3 , 4 , 3 , 2 );
float f[] = { 2.3 , 4.5 , 6.6 };
char [] c = new char ();
6.6
How do you access elements in an array? What is an array indexed variable?
6.7
What is the array index type? What is the lowest index? What is the representation of
the third element in an array named a ?
6.8
Write statements to do the following:
a. Create an array to hold 10 double values.
b. Assign the value 5.5 to the last element in the array.
c. Display the sum of the first two elements.
d. Write a loop that computes the sum of all elements in the array.
 
Search WWH ::




Custom Search