COE211_Lecture15
COE211_Lecture15
Chapter overview
This chapter focuses on
Array declaration and use
Multidimensional arrays
Multidimensional arrays
0 1 2 3 4 5 6 7 8 9
height 79 87 94 82 67 98 87 81 74 91
height[2] = 89;
height[first] = height[first] + 2;
Object reference
height 79 87 94 82 67 98 87 81 74 91
Refer to BasicArray.java
Declaring Arrays
The scores array could be declared as follows:
int[] scores = new int[10];
The type of the variable scores
is int[] (an array of integers)
Note that the array type
does not specify its size,
but each object of that type has a specific size
boolean[] flags;
Multidimensional arrays
Refer to Invalidindex.java
Off-by-one errors
For example,
if the array codes can hold 100 values
it can be indexed using only the numbers 0 to 99
System.out.println (codes[count]);
It’s common to introduce off-by-one errors
when using arrays
problem
Useful in situations where you don’t know the size of the array
Refer to ReverseOrder.java
Read a list of numbers from the user
=> The idea is to instantiate and fill the array in one step
Multidimensional arrays
words -
-
-
-
-
After a few object creation
After some String objects
are created
words “friendship
”“loyalty”
“honor”
-
-
String literals
Keep in mind
String objects can be created using string literals
Each with
a string representation and
In which case
The method may permanently change an element of the array
if (list.length != 0)
{
int sum = 0;
for (int num : list)
sum += num;
result = (double)num / list.length;
}
return result;
}
Method Overloading
println (String s)
println (int i)
println (double d)
and so on...
The following lines invoke different versions of the
println method:
if (list.length != 0)
{
int sum = 0;
for (int num : list)
sum += num;
result = (double)num / list.length;
}
return result;
}
Type of the multiple
parameters
The type of the parameters
can be any primitive or object type
Constructors
Can also be setup
to accept a variable number of parameters