Chapter 4
Chapter 4
Dimensional
Arrays
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.
0132130807
Opening
Problem
• Read one hundred numbers, compute their average, and find
out how many
numbers are above the average.
• Defining 100 variables and writing 100 lines to read is not
practical!
• What if there is a way to create a list of 100 items?
• How to access the items or any item of the list?
• Items on the list have positions.
• The first item is on the first position.
• We will create an indexing system.
• We will refer to each position with its index of the list.
• The first element will be at index 0
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 2
0132130807
Introducing
Arrays
• Array is a data structure that represents a collection of the
same types of data.
double[ ] myList = {5.6,4.5, 3.3, 13.2, 4.08,
34.33, 34.0, 45.45, 99.99, 11.23}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 3
0132130807
Declaring Array
Variables
• Use the square brackets [ ] to tell the compiler this is a list not a
single data item.
• To declare an array, use the following syntax datatype[] arrayName;
double[]
• Example:myList;
•datatype arrayRefVar[]; // This style is allowed, but not
preferred
double
Example: myList[];
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 4
0132130807
Creating
Arrays
Index
• arrayName = new
datatype[arraySize]; 0 9
• Example:
myList = new
double[10];
• new reserves 10 positions of the double-
• double[10] type size.
myList[0 references the first element in
• ]
myList[9 the array.
] references the last element in
the array.
Declaring and Creating in
•One Step arrayRefVar = new
datatype[]
datatype[arraySize];
double[] myList = new
double[10];
• datatype arrayRefVar[] = new
datatype[arraySize];
double myList[] = new
double[10];
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 5
0132130807
The Length or size of an
Array
• Once an array is created, its size is fixed. It cannot be changed. You can
find its size using
arrayname.length
• For example,
• myList.length;
returns 10
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 6
0132130807
Default Values of array elements
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 7
0132130807
Indexed
Variables
• The array elements are accessed through the index.
• The array indices are 0-based, i.e., Array starts from 0 to
arrayRefVar.length-1.
• In the example in Figure 6.1, myList holds ten double values and the
indices are from 0 to 9.
• Each element in the array is represented using the following syntax,
known as an indexed variable:
myList = new
– double[10];
arrayName[index];
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 8
0132130807
Using Indexed
Variables
• After an array is created, an indexed variable can be used in the same way
as a regular variable.
• For example,
• the following code adds the value in
• myList[0] and myList[1] to myList[2].
myList[2] = myList[0] +
myList[1];
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 9
0132130807
Array
Initializers
• Declaring, creating, initializing in
one step:
double[] myList = {1.9, 2.9, 3.4,
3.8};
int[] myList = {1, 2, 4, 5, 8,
9};
char[] myList = {‘a’, ‘b’,
‘c’};
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 10
0132130807
Declaring, creating, initializing Using the
Shorthand Notation
double[] myList = {1.9, 2.9, 3.4,
3.5};
• This shorthand notation is equivalent to the following
statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 11
0132130807
CAUTIO
N
• Using the shorthand notation, you have to declare, create, and
initialize the array all in
one statement. Splitting it would cause a syntax error.
• Fordouble[]
example, the following is wrong:
myList;
myList = {1.9, 2.9, 3.4,
3.5};
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 12
0132130807
WAP in Java to get array size, sum of array elements &
average of array elements
public class Exercise
{
public static void main(String[] args)
{
int[] numbers = new int[] {20, 30, 25, 35, 16, 60, 100};
//calculate sum of all array elements
int sum = 0;
for(int i=0; i < numbers.length; i++). //index i //
sum = sum + numbers[i];
//calculate average value
double average = sum / numbers.length;
System.out.println(”Size of the array elements is : " +numbers.length);
System.out.println("Sum value of the array elements is : " +sum);
System.out.println("Average value of the array elements is : " +average);
}
}
OUTPUT:
Total number of the array elements is : 7
Sum value of the array elements is : 286
Average value of the array elements is : 40.0
Trace Program with Declare array variable values, create an
Arrays array, and assign its reference to
values
public class Test {
public static void main(String[]
args)
int[]{ values = new int[5];
After the array is created
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1]; 0 0
0
} 1
2 0
values[0] = values[1] + 3 0
values[4]; 4 0
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 14
0132130807
Trace Program with i ( =5) < 5 is false. Exit the loop
Arrays
public class Test {
public static void main(String[]
args) { int[] values = new
After the fourth iteration
int[5];
for (int i = 1; i < 5; i++) { 0 0
1
values[i] = i + values[i-1]; 1
2 3
} 3 6
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 15
0132130807
Trace Program with i ( =5) < 5 is false. Exit the loop
Arrays
public class Test {
public static void main(String[]
args) { int[] values = new
After the fourth iteration
int[5];
for (int i = 1; i < 5; i++) { 0 11
1
values[i] = i + values[i-1]; 1
2 3
} values[0] = values[1] + 3 6
} values[4]; 4 10
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 16
0132130807
Processing
Arrays
• There are many situations where using arrays is the only way to
solve a problem
• To process the items in stored in the array, you must loop
through the array.
– See the examples in the text to check the followings:
• (Initializing arrays with input values)
• (Initializing arrays with random values)
• (Printing arrays)
• (Sum all elements)
• (Finding the largest element of array)
• (Finding the smallest index of the largest element)
• (Shifting elements of array)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 17
0132130807
Exampl double[] myList = {1.9, 2.9, 3.4,
es 3.5};
//Initializing arrays with input values
java.util.Scanner input = new
java.util.Scanner(System.in); System.out.print("Enter
" + myList.length + " values: "); for (int i = 0; i <
myList.length; i++)
myList[i] = input.nextDouble();
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 20
0132130807
Enhanced for Loop (for-each
loop)
double[] myList = {1.9, 2.9, 3.4,
3.5};
• Java(JDK 1.5) supports a convenient for loop, known as a for-each loop or
enhanced for loop,
which enables you to traverse the array sequentially without using an index
variable.
for (int
• For example, the following code displays i elements
all the = 0; i in
< the
myList.length;
array
myList: i++)
• You can read the code as “for each element u in myList do the
following.”
• Note that: the variable, u, must be declared the same type as the
elements in myList.
• In general, the syntax for a for-each loop is
• 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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 21
0132130807
WAP foreach-loop vs for-loop for display the arrray elements
class HelloWorld
{
public static void main(String[] args)
{
int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] num = new int[] {1, 2, 3, 4, 5};
int sum = 0;
for(int i=0; i < numbers.length; i++) //+,-, *, /, // calulation//
sum = sum + numbers[i];
System.out.println("Sum value of the array elements is : " +sum);
}
}
WAP by using method to find the maximum of elements in an Array
public class MaxInArray
{
public static void main(String[] args)
{
int[] numbers = {3, 5, 1, 8, 4, 2};
int max = findMax(numbers);
System.out.println("The maximum value in the array is: " + max);
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 27
0132130807
Copying
Arrays
• In Java, you can use assignment statements to copy primitive data type
variables, butlist2
not arrays.
= does not copy the contents of the array
• This statementlist1; referenced by list1 to
• list2,
But, copies the reference value ( the address of the location in the memory)
from list1 to list2.
• After this statement, list1 and list2 reference to the same array.
• The array previously referenced by list2 is no longer referenced; it becomes
garbage, which will
be automatically collected by the Java Virtual Machine.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 28
0132130807
Copying
Arrays
//Method1. Using a
loop int[] = {2, 3, 1, 5, 10};
sourceArray
int[] = new
targetArray int[sourceArray.length];
for (int i = 0; < sourceArrays.length; i++)
i
targetArray[i] = sourceArray[i];
//Method2. Using the arraycopy utility
//Syntax: Arraycopy (sourceArray, src_pos, targetArray, tar_pos,
length);
// see the following example:
System.arraycopy(sourceArray, 0, targetArray, 0,
sourceArray.length);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 29
0132130807
WAP to copy array element form source array to target array.
import java.util.ArrayList;
import java.util.Collections;
class List
{
public static void main(String args[])
{
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new int[sourceArray.length];
for (int i = 0; i < sourceArray.length; i++)
targetArray[i] = sourceArray[i];
System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);
for (int i = 0; i < targetArray.length; i++) // for-loop to display target
array//
System.out.print(targetArray[i] +" ");
}
}
WAP to copy array element form source array to
target array
import java.util.ArrayList;
import java.util.Collections;
class List
{
public static void main(String args[])
{
int[] sourceArray = {2, 3, 1, 5, 10, 7, 9, 10};
int[] targetArray = {2, 2, 2, 2, 2, 2, 2, 2} ;
System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length); //syntax for copy
array
for (int i = 0; i < targetArray.length; i++)
System.out.print(targetArray[i] +" ");
}
}
OUTPUT: 2, 3, 1, 5, 10, 7, 9, 10
Passing Arrays to
Methods
public static void printArray( int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
2};
printArray (list);
//Example2. Invoke
the method
printArray( new
int[]{3, 1, 2, 6, 4,
2} Programming,
Liang, Introduction to Java ); Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 32
0132130807
WAP to passing array elements to the the method in java
import java.util.ArrayList;
import java.util.Collections;
class List
{
public static void printArray( int[] array)
{
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i] + " ");
}
}
OUTPUT: 3, 1, 2, 6, 4, 2, 8
8. Write a Java program to create a new array list, add the following data {PHP, Java, C++, Python}
and print out the collection.
a. Insert element JavaScript into the array list at the index one.
b. Remove the third element from array list.
c. Sort the array list.
d. Use for loop or for each to display all elements from the array list
import java.util.ArrayList;
import java.util.Collections;
class List
{
public static void main(String args[])
{
ArrayList<String> list = new ArrayList<>();
list.add("PHP");
list.add("Java");
list.add("C++");
list.add("Python");
String list = {“PHP”, “Java”, “C++”, “Python”};
list.add(1,"JavaScript"); //a
list.remove(2); //b
Collections.sort(list); //c
for(String x: list) //d
{
System.out.println(x);
}
}}
OUTPUT:
C++
JavaScript
PHP
Python
Pass By
Value
• Java uses pass-by-value to pass arguments to a method.
• There are important differences between passing the values of
variables of primitive
data types and passing arrays.
– For an argument of a primitive type, the argument’s value is
passed.
– For an argument of an array type, the value of the argument is
a reference to an array; this reference value is passed to the
method.
– Semantically, it can be best described as pass-by-sharing, that
is, the array in the method is the same as the array being
passed.
• Thus, if you change the array in the method, you will see the
change outside the method.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 35
0132130807
Simple
Example
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 36
0132130807
WAP in java for Pass By Value in array.
class A
{
public static void main(String args[])
{
int x = 5; // variable declaration//
int[] y = new int [10]; // no value but has size 10 of array
Moosa(x,y);
System.out.println("x is :" +x);
System.out.println("y[0] is :" +y[0]);
}
public static void Moosa(int n, int[] m)
{
n =10;
m[0]= 1111111;
}
}
OUTPUT
x is :5
y[0] is :1111111
Call Stack: It is one of the types of memory to store the
initialize value.
• When invoking m(x, y), the values of x and y are passed to number and numbers.
Since y contains
the reference value to the array, numbers now contains the same reference value
to the same array.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 38
0132130807
Call
Stack
• When invoking m(x, y), the values of x and y are passed to number and numbers.
Since y contains the
reference value to the array, numbers now contains the same reference value to
the same
Stac array. Hea
k p
Space required
for method m
int[] The arrays
numbers:
int number:reference 555 are stored in
1001 5
Space required for 0 a heap.
the main method
int[] reference Array of ten int
y: int values is stored
x: 1 0 here
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 39
0132130807
Hea
p
• The Java Virtual Machine stores the array in an area of memory, called heap, which
is used for
dynamic memory allocation where blocks of memory are allocated and freed in an
arbitrary order.
Heap
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 40
0132130807
Returning an Array from a
Method
• int[] list1 = new int[]{1, 2, 3, 4, 5,
6};
• int[] list2 = reverse(list1);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 41
0132130807
WAP for reverse array elements by using swapping in
java.
public
{
class ReverseArray
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 44
0132130807
Any
Questions?
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.
0132130807