Java Reference
In-Depth Information
// A runtime error. salary is not referring to any array object yet.
int len = salary.length;
// Create an int array of length 1000 and assign its reference to salary
salary = new int[1000];
// Correct. len2 has a value 1000
int len2 = salary.length;
Typically, elements of arrays are accessed using loops. If you want to do any processing with all of the elements
of an array, you execute a loop starting from index 0 (zero) to length minus 1. For example, to assign the values 10, 20,
30, 40, and 50 to the elements of the empId array of length 5, you would execute a for loop as shown:
for (int i = 0 ; i < empId.length; i++) {
empId[i] = (i + 1) * 10;
}
It is important to note that while executing the loop, the loop condition must check for array index/subscript
for being less than the length of array as in "i < empId.length" because the array index starts with 0, not 1. Another
common mistake made by programmers while processing an array using a for loop is to start the loop counter at 1 as
opposed to 0. What will happen if you change the initialization part of the for loop in the above code from int i = 0 to
int i = 1 ? It would not give you any errors. However, the first element, empId[0] , would not be processed and would
not be assigned the value of 10.
You cannot change the length of an array after it is created. You may be tempted to modify the length property.
int[] roll = new int[5]; // Create an array of 5 elements
// A compile-time error. The length property of an array is final. You cannot modify it.
roll.length = 10;
You can have a zero-length array. Such an array is called an empty array.
// Create an array of length zero
int[] emptyArray = new int[0];
// Will assign zero to len
int len = emptyArray.length;
arrays use zero-based indexing. that is, the first element of an array has an index of zero. arrays are created
dynamically at runtime. the length of an array cannot be modified after it has been created. If you need to modify the
length of an array, you must create a new array and copy the elements from the old array to the new array. It is valid to
create an array of length zero.
Tip
Initializing Array Elements
Recall from Chapter 6 that, unlike class member variables (instance and static variables), local variables are not
initialized by default. You cannot access a local variable in your code unless it has been assigned a value. The same
rule applies to the blank final variables. The compiler uses Rules of Definite Assignment to make sure that all variables
have been initialized before their values are used in a program.
 
 
Search WWH ::




Custom Search