Docsity

Using Arrays with Methods in Java, Slides of Java Programming

Partial preview of the text

Download Using Arrays with Methods in Java and more Slides Java Programming in PDF only on Docsity!

Using Arrays with Methods

in Java

Review - What is an Array?

Recall: An array is a collection of one type of data

(e.g., integer, string) that is used for a single

purpose (e.g., grades, addresses).

Each box is called an element of the array, and

the position of each element is the index.

0 1 2 3 4

an array with 5 elements

Arrays in Java

An array in Java is typically declared in one step:

dataType name = new dataType[size];

name โ€“ the name of the array

dataType โ€“ int, char, double, String, etc...

new โ€“ tells Java to create space in memory

size โ€“ the number of items, or elements, in array

Example โ€“ Passing a Specific

Array to a Function

public static void printArray (int[] array) { for int i = 0; i < array.length; i++) { System.out.println(array[i]); } }

public static void main(String[] args) { int[] numbers = new int[10];

% initialize the array for int i = 0; i < numbers.length; i++) { numbers[i] = 2*i โ€“ 3; }

printArray(numbers); }

Changing Data using Methods

When an array is passed to a method, a copy of

the address of the array (i.e., the location of the

data in memory) is made. The actual data,

however, is referenced using this address, so it is

not protected and may be changed.

int[] numbers = {1, 2, 3, 4, 5};

printArray(numbers); // output is 1, 2, 3, 4, 5 increaseByOne(numbers); // adds 1 to each element printArray(numbers); // output is 2, 3, 4, 5, 6