JAVA ARRAYS

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

What is the output?

6

one

. How many loops are necessary to find the largest number in an array?

x = some positive number (x=0? @Nov2 ex 2 notes)

. If data = "Z", what is the value of x in the expression x = data.compareTo("B") ?

x = 10 (the last makes it find the last en)

. Suppose data is the string "BrokenBroken" What is the value of x in the expression x =data.lastIndexOf("en")?

spreadsheet + tabs = 3d simulations moderating in science/engineering. double[][][] data = new double[4][1000][100]; 4d is dealing with time.

A 3-d array is useful for? example?

varying, parameters

A Java method can be defined to accept a ___ number of ___ .

style 1: int[ ] numbers; style 2: int numbers[ ]; int numbers[ ], codes[ ], scores[ ];

Alternate Array Declaration Notation

initializer

An ____ list can be used, instead of the new operator, to instantiate an array object.

N - 1

An array of Size N is indexed from 0 to what?

parameter, alias

An entire array can be passed as a ____ , making the formal parameter an ___ of the original.

A data structure for storing a collection of data of the same type

Array

String numbers[][] = { {"Tom", "555-3322"}, {"Sam", "555-8976"}. {"Cole", "596-2142"} };

Create an appropriate array to hold the names and phone numbers of 3 people.

- Create ArrayList<String> nameList = new ArrayList<String>();

Create and Use an ArrayList Object

String data[] = {"This", "is", "great"};

Create and fill an array with the strings "This", "is", and "great"

- It is not required that the name of main's parameter array be args. You can name it anything you wish. It is a standard convention, however, for the name args to be used -

Command-line Arguments

When you invoke a Java program from the operating system command line, you can specify arguments that are passed into the main method of the program. In addition, you can write a method that takes a variable number of arguments. When the method runs, it can determine the number of arguments that were passed to it and act accordingly

Command-line arguments and variable-length argument lists

1. Using an invalid subscript. Java does not allow you to use a subscript value that is outside the range of valid subscripts for an array. 2. Confusing the contents of an integer array element with the element's subscript. An element's subscript and the value stored in the element are not the same thing. The subscript identifies an element, which holds a value. 3. Causing an off-by-one error. When processing arrays, the subscripts start at zero and end at one less than the number of elements in the array. Off-by-one errors are commonly caused when a loop uses an initial subscript of one and/or uses a maximum subscript that is equal to the number of elements in the array. 4. Using the = operator to copy an array. Assigning one array reference variable to another with the = operator merely copies the address in one variable to the other. To copy an array, you should copy the individual elements of one array to another. 5. Using the = operator to copy an array. Assigning one array reference variable to another with the = operator merely copies the address in one variable to the other. To copy an array, you should copy the individual elements of one array to another. 6. Reversing the row and column subscripts when processing a two-dimensional array. When thinking of a two-dimensional array as having rows and columns, the first subscript accesses a row and the second subscript accesses a column. If you reverse these subscripts, you will access the wrong element

Common Errors to Avoid

- To compare the contents of two arrays, you must compare the elements of the two arrays. // First determine whether the arrays are the same size. if (firstArray.length != secondArray.length) arraysEqual = false; // Next determine whether the elements contain the same data. while (arraysEqual && index < firstArray.length) { if (firstArray[index] != secondArray[index]) arraysEqual = false; index++; } if (arraysEqual) System.out.println("The arrays are equal."); else System.out.println("The arrays are not equal.");

Comparing Arrays

- reference copy: both the array1 and array2 variables will reference the same array. - Only the address of the array object is copied, not the contents of the array object.

Copying Arrays

Yes.

Does auto-boxing work inside arithmetic expressions?

An array that varies in size at run time.

Dynamic Array

It cuts the list in half and then in half over and over again, comparing if the target value is above or below the middle value.

Explain how a binary search works starts with a sorted list and cuts in half over and over while making comparisons

Goes through items and compares

Explain how a linear search works

Whenever a reference is made to a particular array element, the index operator (the brackets that enclose the subscript) ensures that the value of the index is greater than or equal to zero and less than the size of the array. If it is not within the valid range, an ArrayIndexOutOfBoundsException is thrown.

Explain the concept of array bounds checking. What happens when a Java array is indexed with an invalid value?

It compares values at two index locations and does a swap if necessary. It repeats this process over and over. You need two loops

Explain what a Bubble sort is and how does it word? How many loop do you need?

objects

How are arrays implemented?

for (int i = 0; i < ROWS; i++) for (int j = 0; j < COLUMNS; j++) board[i][j] = " ";

How to fill or search a 2D array.

a) .length b) .size() c) .length()

How to find the number of elements in: a) an Array b) an ArrayList c) a String

a) .length b) .size() c) .length()

How to find the number of elements in: a) an Array b) an ArrayList c) a String

arrayRefVar.length. For example: myList.length is 10

How to obtain the size of an array

When the rows of a two-dimensional array are of different lengths, the array is known as a ragged array - You create a ragged array by first creating a two-dimensional array with a specific number of rows, but no columns.

Ragged arrays

x =7 y = 4 z = 2

Referring to #21, if x = bus.length, y = bus[0].length, and z = bus[1].length, what are the values for x , y, and z?

The ArrayList class has a remove method that removes an item at a specific index. You pass the index as an argument to the method. nameList.remove(1);

Remove an Item from an ArrayList

An algorithm for searching an array in which each element of the array is checked one after the other.

Linear Search

String statement = new String("Hello");

List a way to construct a string

String statement = "Hello";

List an easier way to construct a string

The ArrayList class's set method can be used to replace an item at a specific index with another item nameList.set(1, "Becky");

Replacing an item

In addition to accepting arrays as arguments, methods may also return arrays. public static double[] getArray() { double[] array = { 1.2, 2.3, 4.5, 6.7, 8.9 }; return array; } values = getArray();

Returning Arrays from methods

assigns the consecutive blocks of memory to a process requesting for memory

contiguous memory allocation

Arrays.copyOf(<source array>, <length>);

copyOf syntax

Copies array elements within the array, to and from specified positions

copyWithin()

how to create a copy of an array that is not an alias?

create a new list and use a for loop

Declaring Arrays I An array of letters char[] letters; letters = new char [26]; I An array of String objects String [] dictionary = new String [480000]; I An array of Song objects Song[] playlist = new Song [3]; I An array of Card objects Card[] deckOfCards = new Card [52]; I An array of boolean objects boolean [] lightSwitches = new boolean [100];

create an array of letters: of string objects: of song objects: of card object: of boolean objects:

int size=cup.length; cup[size-1]=23;

cup is an array of doubles. It has more than 50 values, like 1, 2.5, 4.2 cc. Set the last element to 23 cc.

cup[ cup.length - 1 ]=9;

cup is an array. It has many elements like 2, 3.3, 4 cc. Set the last element to 9 cc.

size=cup.length;

cup is an array. It has many sizes, like 1, 2.5, 7.2 cc. Set size = the number of elements in cup.

cup[1]=3.5;

cup is an array. It has more than 50 sizes, like 1, 2.5 cc. Set the 2nd element to 3.5 cc.

cup[9]=13;

cup is an array. It has more than 50 sizes, like 1, 2.5, 8.2 cc. Set the 10th element to 13 cc.

cup is an array. It has many elements like 2.2, 3.3, 14.5 cc. Set the last element to 9 cc.

cup[ cup.length - 1 ]=9;

cup is an array with values like 1.0, 2.5, 4.2 cc. Set the 1st element to 23 cc.

cup[0]=23;

cup is an array with values like 1.0, 2.5, 4.2 cc. Set the 2nd element to 3.5 cc.

cup[1]=3.5;

cup is an array with values like 1.0, 2.5, 4.2 cc. Set the 10th element to 13 cc.

cup[9]=13;

To declare a reference to the array:

dataType [] arrayName;

array specific instantiation syntax

datatype [] arrayName = { value0, value1, ...};

first step of creating an array

declaring the reference to the array

If <length> is longer than the length of the source array, the extra elements are given the _____ _______.

default values

default value for numeric primitive data types is 0 \u0000 for char types and false for boolean types.

default values for arrays

A program that does the same thing every time it is invoked.

deterministic

you are no longer required to write the data type in the part of the statement that calls the ArrayList constructor. Instead, you can simply write a set of empty angled brackets ArrayList<String> list = new ArrayList<>();

diamond operator

Declare cup array. It has 50 elements like 2.0, 3.3, 4.0 cc.

double[] cup=new double[50];

Declare cup array. It has elements 2.0, 3.3, 4.12 cc.

double[] cup={2, 3.3, 4};

price.length()-1 h>0 h--

double[] price={ 1.2, 3.4, 8.3, 2.5, 0.1, 7.7}; Print array backward from the last element to the first? for (int h = ________; h>0 ; ______ ) { ....System.out.print( str[ h ]); }

arrays are more ____ than lists

efficient

One of the values in an array. The[]operator selects elements.

element

each variable on the array is an

element

The type of data that can be stored as an element in a particular array.

element type

An alternative syntax for traversing the elements (values) of an array.

enhanced for loop

Returns true if a and b have the same length and the elements of in corresponding indexes match and false otherwise.

equals method

booleanArrays.equals(a, b)

equals syntax

Checks if every element in an array pass a test

every()

boolean default value

false

Fill the elements in an array with a static value

fill()

Creates a new array with every element in an array that pass a test

filter()

y.length big

find the largest number: int big=y[0]; for(int i=0; i<_________; i++) { . . . . if(big<y[i]) . . . . { . . . . ______ = y[i]; . . . . } }

y.length big

find the largest number: int big=y[0]; for(int i=0; i<_________; i++) { ........if(big<y[i]) ........{ ............______ = y[i]; ........} }

k myArray.length

find the largest number: int huge=myArray[0]; for(int ____=0; k<_________; k++) { ........if(huge<myArray[k]) ........{ ............huge = myArray[k]; ........} }

myArray.length myArray[k]

find the largest number: int huge=myArray[0]; for(int k=0; k<_________; k++) { ........if(huge<myArray[k]) ........{ ............huge = _________; ........} }

mm+1 largest

find the largest number: int largest=g[0]; for(int mm=0; mm<g.length; mm=___) { ........if(_______<g[mm]) ........{ ............largest = g[mm]; ........} }

largest x[i]

find the largest number: int largest=x[0]; for(int i=0; i<x.length; i++) { ........if(_______<x[i]) ........{ ............largest = _______; ........} }

x.length mm++

find the largest number: int largest=x[0]; for(int mm=0; mm<_________; ______) { ........if(largest<x[mm]) ........{ ............largest = x[mm]; ........} }

1 largest

find the largest number: int largest=x[0]; for(int mm=0; mm<x.length; mm+=___) { ........if(_______<x[mm]) ........{ ............largest = x[mm]; ........} }

Returns the value of the first element in an array that pass a test

find()

Returns the index of the first element in an array that pass a test

findIndex()

you can only specifically instantiate an array when it is ___ declared

first

________ [ ] xyz = new Movie[10]

Movie

During the loop's execution, the variable index takes on the values 1 through 100, when it should take on the values 0 through 99. As a result, the first element, which is at subscript 0, is skipped. In addition, the loop attempts to use 100 as a subscript during the last iteration. Because 100 is an invalid subscript, the program will throw an exception and halt.

Off-by-One Errors

Individual array elements are processed like any other type of variable. grossPay = hours[3] * payRate; - When using increment and decrement operators, be careful not to use the operator on the subscript when you intend to use it on the array element

Processing Array Elements

the size of a python list can change, but an array has a

fixed size

Returns the string without leading or trailing whitespace

String trim()

Convert a StringBuilder into a String

String(StringBuilder builder)

Convert a char array into a String

String(char[] array)

Declare array named schoolDays. Elements are mo, tu, we, th, fr (in that order).

String[ ] schoolDays = {"mo", "tu", "we", "th", "fi"};

Declare array named wkEnd. Elements are sat and sun.

String[ ] wkEnd = {"sat", "sun"};

Declare mth array for the months of the year.

String[] mth=new String[12];

snack is an array of 50 food names. Declare this array.

String[] snack=new String[50];

Declare snack array. It has elements "gum", "chips".

String[] snack={"gum", "chips"};

Declare array week. It has 7 elements with names of the days of the week.

String[] week = new String[7];

nested loops. The outer loop controls the column subscript and the inner loop controls the row subscript. The inner loop calculates the sum of a column, which is stored in an accumulator.

Summing the columns of a two-dimensional array

int total; // Accumulator for (int row = 0; row < numbers.length; row++) { // Set the accumulator to 0. total = 0; // Sum a row. for (int col = 0; col < numbers[row].length; col++) total += numbers[row][col]; // Display the row's total. System.out.println("Total of row " + row + " is " + total); }

Summing the rows of a two-dimensional array

"part" would be a string. In this case, the variable is "ken"

Suppose data is the string "Broken" What is the value of part in the expression: part = data.substring(3,6); ? What type of variable is part?

x will be some negative number because broken is shorter than summer

Suppose data is the string "Broken" What is the value of x in the expression x = data.compareTo("Summer") ?

x will be some negative number, because there is no match

Suppose data is the string "Broken". What is the value of x in the expression x = data.compareTo("Summer"); ?

x = 4

Suppose data is the string "BrokenBroken" What is the value of x in the expression x = data.indexOf("en"); ?

x = 10

Suppose data is the string "BrokenBroken" What is the value of x in the expression x = data.lastIndexOf("en") ?

x = -1

Suppose data is the string "BrokenBroken" What is the value of x in the expression x = data.lastIndexOf("on") ?

x = 4 finds the first match

Suppose data is the string "BrokenBroken" What is the value of x in the expression x =data.indexOf("en") ?

x = -1 since it's not found

Suppose data is the string "BrokenBroken" What is the value of x in the expression x =data.lastIndexOf("on")?

z is an integer and in this case z = 10

Suppose data is the string "finish now" What does the following do, z = data.length(), and what type is the variable z?

z is an integer and in this case z = 10

Suppose data is the string "finish now". What does the following do? z = data.length(); What type is the variable z?

returns the character

Suppose data is the string "open now." What does ch = data.charAt(8) return?

"False," because all the characters must match for it to be true.

Suppose the test against the the string is "supal," what value does y have? (Refer to #45)

50

Suppose you are thinking of a number from 0 to 100, what is the first number that it's compared to if searching in binary?

(Option C) You are causing num1 to reference num2

Suppose you have two arrays: num1 and num2. What does: num1 = num2 do?

Accessing each element of an array is called ___ an array.

Traversing

fixed, length

When an array is created it has a ____ size. The size of the array is a public constant named ___.

double the size so we don't have to do the copying again.

When creating arrays, it's good practice to do what with each addition to the array.

braces

When initializing a two-dimensional array, you enclose each row's initialization list in...

java interpreter throws an ArrayIndexOutOfBondsException called bounds checking

When we try to access an element in an array out of bounds what happens? Which is called what?

Zero.

When you construct an ArrayList object, it has a size of?

binary

Which search routine is faster for sorted data?

They group together related data, organize data, and assist in the sorting and searching of data

Why are arrays convenient?

A class that wraps primitive values in an object.

Wrapper class

a) Boolean b) Integer c) Double

Wrapper classes for: a) boolean b) int c) double

a) Boolean b) Integer c) Double

Wrapper classes for: a) boolean b) int c) double

A command-line argument consists of data included on the command line when the interpreter is invoked to execute the program. Command-line arguments are another way to provide input to a program. They are accessed using the array of strings that is passed into the main method as a parameter.

What is a command-line argument?

A test suite is a set of tests for repeated testing.

What is a test suite?

An array's element type is the type of values that the array can hold. All values in a particular array have the same type, or are at least of compatible types. Thus we might have an array of integers, or an array of boolean values, or an array of Dog objects, and so on.

What is an array's element type?

A set of data of the same type referenced with a common name

What is an array?

An array is an object that stores a list of values. The entire list can be referenced by its name, and each element in the list can be referenced individually based on its position in the array.

What is an array?

a set of data of the same type referenced with a common name

What is an array?

It would be an array that has a different number of columns for each row. int bus[][] = new int[7][]; bus[0] = new int[4]; //on Mondays you can hold 4 data pts bus[1] = new int[2]; // on Tuesday, 2 data pts bus[2] = new int[4]; //Wednesday hold 4 data points //etc.

What is an irregular array and give an example of declaring one called bus for a bus schedule that just runs M, W, F for 4 times each day, on Tues, Thurs, and Sat twice, and Sun once.

An off-by-one error occurs when a program's logic exceeds the boundary of an array (or similar structure) by one. These errors include forgetting to process a boundary element, as well as attempting to process a nonexistent element. Array processing is susceptible to off-by-one errors because their indexes begin at zero and run to one less than the ssize of the array.

What is an off-by-one error? How is it related to arrays?

Called the set method. Overwrites index i with a. Nothing else is moved. Size stays the same.

What does this do? arrayListReference.set(i, a);

Called the size method. Returns the size of the array list. The last valid index is arrayListReference.size() - 1.

What does this do? arrayListReference.size();

Both arrays are now pointing to the same reference.

What does this do? double[] data = new double[10]; . . . // Fill array double[] prices = data;

SMALL SMALL BIG SMALL SMALL

What does this print? int[] x={ 3, 7, 1, 9, 4, 0, 2 }; int[] y={ 0, 7, 3, 1, 9, 4, 9 }; for( int j=1; j<=5; j++ ) { ....if( x[ j ] > y[ j ] ) ....{ ........System.out.print("BIG ") ....} ....else ....{ ........System.out.print( "SMALL " ); ....} }

SMALL BIG SMALL

What does this print? int[] x={ 3, 7, 1, 9, 4, 0, 2 }; int[] y={ 0, 7, 3, 1, 9, 4, 9 }; for( int pp= 1; pp<=5; pp=pp+2 ) { . . . . if( x[ pp ] > y[ pp ] ) . . . . { . . . . . . . . System.out.print("BIG ") . . . . } . . . . else . . . . { . . . . . . . . System.out.print( "SMALL " ); . . . . } }

The length field. It is an instance variable of the array.

What field returns the number of elements in an array?

Two-dimensional arrays form a tabular, two-dimensional arrangement. You access elements with an index pair a[i][j].

What is a 2D array?

n=0; for (int d=0; d< 2; d++) for (int c=0; c< 3; c++) for (int r=0; r<2; r++) g[r][c][d] = n; n = n + 2;

Write a piece of code to initial an array called g that's 2X3X2 to even numbers starting with zero.

10 and 16

What is at location g[1][2][0]?10 What about g[0][1][1]? int[][][] = { { {0,12,4}, {4,16,5}, {8,20,6}}, {{2,14,7}, {6,18,8}, {10,22,9}} };

Conversion between primitive types and the corresponding wrapper classes is automatic.

What is auto-boxing?

Regression testing involves repeating previously run tests to ensure that known failures of prior versions do not appear in new versions of the software.

What is regression testing?

Index

What is the term that describes the items that is used to access a value in an array?

index

What is the term that describes the items that is used to access a value in an array?

0 or a positive integer (no negatives or decimals)

What kind of number is the index value for an array?

0, or a positive integer

What kind of number is the index value for an array?

Only holds objects. Can grow and shrink as needed. Supplies methods for inserting and removing objects. More overhead.

What makes an array list different from an array?

Index out of bounds

What message do you get if you go beyond the index range of an array?

index out of bounds

What message do you get if you go beyond the index range of an array?

int temp[] = new int[3];

What single line of code can be used to declare a 1D array called temp to hold 3 items?

Irregular

What type of an array would you use to hold the hours you work each day for a part time job (assume you work diff numbers of hours each day)?

irregular

What type of an array would you use to hold the hours you work each day for a part time job (assume you work diff numbers of hours each day)?

2D [22][2] in this case the row is the student number, if you had 22 in the class

What type of an array would you use to hold the weight and height of students in the class of 2010?

An array of integers where each integer counts the number of values that fall into a certain range.

histogram

An integer used to specify a specific element in an array.

index

An integer variable or value used to indicate an element of an array.

index

specifies the position of each element in the array

index

Search the array for an element and returns its position

indexOf()

In java, arrays are objects so they contain more ____, but the data is stored in ______

information, consecutive memory

A list of values delimited by braces and separated by commas, used to initialize the values stored in an array.

initializer list

you may ____ into the middle of a python list, but not into an array

insert

second step of creating an array

instantiating the array

array type: int [] array name: scores creates new array object:new type and size: int[5];

int [] scores = new int[5]; break this array down: what is each part ?

Alphabetically compares two strings and returns value < 1 if this string comes before the argument string, 0 if they're equal, and value > if this string comes after

int compareTo(String anotherString)

Returns the hash code of a String

int hashCode()

Returns the index of the first occurrence of the specified substring

int indexOf(String s)

Returns the index of the first occurrence of the specified character

int indexOf(int ch)

Returns the index of the last occurrence of the specified substring

int lastIndexOf(String s)

Returns the index of the last occurrence of the specified character

int lastIndexOf(int ch)

Returns the length of the String

int length()

3 4

int myArray[] = {3, 4, 5, 6}; for(int qq=0; qq<myArray.length; qq++) { ....if(myArray[qq]>4) ....{ ........break; ....} ....System.out.print(myArray[qq] + " "); }

9

int myArray[] = {9, 3, 7, 2, 1, 8}; for(int qq=0; qq<myArray.length; qq++) { ....if(myArray[qq]<5) ....{ ........break; ....} ....System.out.print(myArray[qq] + " "); }

9 7 8

int myArray[] = {9, 3, 7, 2, 1, 8}; for(int qq=0; qq<myArray.length; qq++) { ....if(myArray[qq]<5) ....{ ........continue; ....} ....System.out.print(myArray[qq] + " "); }

int g[][][] = new int[3][2][4]

What type of array would you use to hold all of your final exam grades (assume just 1st and 2nd semester) for all of your high school years. Write a piece of code to declare it.

5, because of the amount of characters

What would x = d.length give for the value of x? (Look at #14)

an array of arrays (like rows & columns); example: int[][] table = new int[3][5]; //note. table.length is rows table[i].length is the [i]'th row in the table.

a 2d array is what?

public static Color[] workWithArrays(Color[] myColor) { Color [] newColors = new Color[myColor.length]; for (int i = 0; i < myColor.length; i++ { Color old = myColor[i]; //deep copy newColors[i] = new Color(old.getRed(), old.getGreen(), old.getBlue()); } return newColors; }

a method for copying color values with an array: deep copy.

to instantiate an array

arrayName = new dataType[ size ];

how to access an element of an array

arrayName[exp]

how to set indexes in an array to values?

arrayName[exp] = value;

Returns true if the String contains the specified String

boolean contains(String s)

Returns true if String ends with the specified String

boolean endsWith(String suffix)

Returns true if String equals another object. Use this to see if two strings are equal.

boolean equals(Object anObject)

Returns true if length of string is 0

boolean isEmpty()

Tests if this string starts with the specified prefix

boolean startsWith(String prefix)

The process that ensures that an index is in the valid range for teh array being referenced. Java performs automatic bounds checking.

bounds checking

size=box.length;

box is an array. It has many sizes, like 1, 2.5, 7.2 cc. Set size = the number of elements in box.

Returns the char at the specified index

char charAt(int index)

Converts this string to a character array

char[] toCharArray()

9 3 7 2

int myArray[] = {9, 3, 7, 2, 1, 8}; for(int qq=0; qq<myArray.length; qq++) { ....if(myArray[qq]==1) ....{ ........break; ....} ....System.out.print(myArray[qq] + " "); }

money[2]=3;

int[] money={34, 21, 5, 9, 12, 43, 2, 17, 8}; Replace 5 with 3

money[3]=3;

int[] money={34, 21, 5, 9, 12, 43, 2, 17, 8}; Replace 9 with 3

Declare x array to hold elements 10, 20, 30, 40.

int[] x = {10, 20, 30,40 };

10 13 4 2

int[] x={ 3, 1, 4, 1, 5, 9, 2 }; for(int j=2; j<=5; j++) { ....System.out.print( x[ j ] + x[ j +1] + " " ); }

4 1

int[] x={ 3, 1, 4, 1, 5, 9, 2 }; for(int j=2; j<=5; j++) { ....if( j == 4 ) ....{ ........break; ....} ....System.out.print( " " + x[ j ] ); }

4 1 9

int[] x={ 3, 1, 4, 1, 5, 9, 2 }; for(int j=2; j<=5; j++) { ....if( j == 4 ) ....{ ........continue; ....} ....System.out.print( " " + x[ j ] ); }

3 -6 1 0

int[] x={ 3, 1, 4, 1, 5, 9, 2 }; int[] y={ 0, 7, 3, 1, 9, 4, 9 }; for(int j=2; j<4; j++) { ....System.out.print( x[ j ] - y[ j ] + " "); }

1 0 -4 5

int[] x={ 3, 1, 4, 1, 5, 9, 2 }; int[] y={ 0, 7, 3, 1, 9, 4, 9 }; for(int j=2; j<=5; j++) { ....System.out.print( x[ j ] - y[ j ] + " "); }

-6 1 0 -4 5

int[] x={ 3, 1, 4, 1, 5, 9, 2 }; int[] z={ 0, 7, 3, 1, 9, 4, 9 }; for(int j=1; j<=5; j++) { ....System.out.print( x[ j ] - z[ j ] + " " ); }

13 10 4

int[] x={ 3, 7, 1, 9, 4, 0, 2 }; int[] y={ 0, 7, 3, 1, 9, 4, 9 }; for(int k=4; k>=2; k--) { . . . . System.out.print( x[ k ] + y[ k ] + " " ); }

1 j<=5 j=j+2

int[] x={ 3, 7, 1, 9, 4, 0, 2 }; int[] y={ 0, 7, 3, 1, 9, 4, 9 }; for(int mm= _____; ______; _______) { . . . . System.out.print( x[ mm ] + y[ mm ] + " " ); } //This is tricky. Fill in the blank so that //it prints 14 10 4

4 10 13

int[] x={ 3, 7, 1, 9, 4, 0, 2 }; int[] y={ 0, 7, 3, 1, 9, 4, 9 }; for(int rr=2; rr<=5; rr++) { ....System.out.print( x[ rr ] + y[ rr ] + " "); }

Checks whether an object is an array

isArray()

Search the array for an element, starting at the end, and returns its position

lastIndexOf()

each array has a read-only integer instance variable named ____ which holds the number of elements in an array

length

first check for if arrays are the same

length

int[] money={34, 21, 5, 9, 12, 43, 2, 17, 8}; Replace 5 with 3

money[2]=3;

amount = movie.length;

movie is an array. It has many items. Set amount = the number of items in movie.

An array with more than one index dimension.

multidimensional array

assigns the separate memory blocks at the different location in memory space in a nonconsecutive manner to a process requesting for memory.

noncontiguous memory allocation

A program that always behaves differently, even when run multiple times with the same input.

nondeterministic

when specifically instantiating an array, what goes inside of the []?

nothing

any object reference default value

null

char default value

null character

Arrays are the most efficient way to store a collection of a known _____ of items

number

Removes the last element of an array, and returns that element

pop()

the equals method works for arrays of _____ types

primitive

the data type in an array can be any of java's ______ or _____

primitive types, classes

use a for loop: for (int index = scores.length() -1; index >= 0; index--; { System.out.println(scores[index]); }

printing an array backwards:

A sequence of numbers that appear to be random, but which are actually the product of a deterministic computation.

pseudorandom

Adds new elements to the end of an array, and returns the new length

push()

A traversal pattern that combines the elements of an array into a single value.

reduce

Reduce the values of an array to a single value (going left-to-right)

reduce()

Reduce the values of an array to a single value (going right-to-left)

reduceRight()

A value (memory address) that indicates another value, like an array. In a state diagram, a reference appears as an arrow.

reference

A value that indicates another value, like an array. In a state diagram, a reference appears as an arrow.

reference

The copyOf method is often used to ______ an array

resize

Reverses the order of the elements in an array

reverse()

Removes the first element of an array, and returns that element

shift()

cup is an array with values like 1.0, 2.5, 4.2 cc. Set size = the number of elements in cup.

size=cup.length;

Selects a part of an array, and returns the new array

slice()

String[] snack=new String[50];

snack is an array of 50 food names. Declare this array.

snack[ snack.length-1 ] ="water";

snack is an array. Set the last item to "water".

snack[10]="gum";

snack is an array. It has more than 50 items, like "fruits", "candy", "chips". Set the 11th item to "gum".

snack[0]="water";

snack is an array. It has more than 50 items, like "fruits", "candy", "chips". Set the 1st element to "water".

snack[1]="water";

snack is an array. It has more than 50 items, like "fruits", "candy", "chips". Set the 2nd item to "water".

howMany=snack.length;

snack is an array. It has more than 50 items. Set howMany = the number of items in snack.

snack is an array. Set the last item to "water".

snack[ snack.length-1 ] ="water";

snack is an array with elements like "fruits", "candy", "chips". Set the 1st element to "water".

snack[0]="water";

snack is an array. It has more than 50 items, like "fruits", "candy", "chips". Set the 11th item to "gum".

snack[10]="gum";

snack is an array. It has more than 50 items, like "fruits", "candy", "chips". Set the 2nd item to "water".

snack[1]="water";

Checks if any of the elements in an array pass a test

some()

the given array using the QuickSort algorithm.

sort method

Sorts the elements of an array

sort()

arrays can also be instantiated by _____ a list of initial values

specifying

Adds/Removes elements from an array

splice()

Returns the String representation of the int (or any other primitive type) argument

static String valueOf(int i)

Sorts an array of Objects according to their natural ordering

static void sort(Object[] arr)

Sorts an int (or any primitive type) array into ascending order. Doesn't return anything

static void sort(int[] arr)

student[1]="Gary";

student is an array. It has more than 50 items, like "Mark", "Abe", "Jane". Set the 2nd item to "Gary".

student[3]="Gary";

student is an array. It has more than 50 items, like "Mark", "Abe", "Jane". Set the 4th item to "Gary".

put Tiger in arraylist called studentName

studentName.add( "Tiger" )

- It is possible to create arrays with multiple dimensions, to model data that occurs in multiple sets double[][][] seats = new double[3][5][8];

three or more dimensions arrays

how do arrays allow random access of elements?

through an index

Converts an array to a string, and returns the result

toString()

Looping through the elements of an array (or other collection).

traversal

An array with two indexed dimensions; it can be thought of as a table with rows and columns.

two-dimensional array

Adds new elements to the beginning of an array, and returns the new length

unshift()

how to access the last element of an array?

use length - 1

when you want to do a calculation. When you want to change the values of the array use a for loop.

use the for each loop in an array/arraylist when you want to do what?

Returns the primitive value of an array

valueOf()

The ellipsis (three periods) that follows the data type indicates that numbers is a special type of parameter public static int sum(int... numbers)

vararg parameter

A parameter list in a method header that allows a variable number of parameters to be passed in, which are stored in an array for processing.

variable-length parameter list

0

when an array is initialized, each list element has an initial value of ?

Given array named xyz. Assign 9 to the last element in xyz .

xyz[ xyz.length -1] = 9;

Because of the size of the elements. Make sure they are all of the same type.

you cannot have arrays with various primitive types or values because why?

String middleName = "Jane"; String [] myNames = { "Mary", middleName, "Watson" }; how many element will the above array have?

3

many implementations of arrays use a

block of contiguous memory

sort works for primitive types except

boolean

Classes for implementing collections.

Collections framework

Yes. import java.util.ArrayList

Do you have to import the ArrayList class to use it?

24

How many data points can array that's 2 x 3 x 4 hold?

24 (2x3x4=24)

How many data points can array that's 2x3x4 hold?

One

How many different variable types can the same array hold?

Converts String to all lowercase

String toLowerCase()

Converts String to all uppercase

String toUpperCase()

1

How many loops are necessary to find the largest number in an array?

Array named days has days of the week. The elements are "mon", "tue", "wed", ... "sun". What is days[3]?

"thu"

byte, short, int default values

0

double default value

0.0d

float default value

0.0f

long default value

0L

array is normally used with an accompanying integer variable that holds the number of items stored in the array. - If a partially filled array is passed as an argument to a method, the variable that holds the count of items in the array must also be passed as an argument. Otherwise, the method will not be able to determine the number of items that are stored in the array

A partially filled

nameList.add("James"); nameList.add("Catherine"); nameList.add("Bill");

Add an item to an ArrayList

- Like regular variables, Java allows you to initialize an array's elements when you create the array. int[ ] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; - This statement declares the reference variable days, creates an array in memory, and stores initial values in the array. The series of values inside the braces and separated with commas is called an initialization list. - Note that you do not use the NEW key word when you use an initialization list - Java allows you to spread the initialization list across multiple lines.

Array Initialization

- Each array in Java has a public field named length. size = temperatures.length; for (int i = 0; i < temperatures.length; i++) System.out.println(temperatures[i]); - You cannot change the value of an array's length field.

Array Length

when the program runs

Array bounds checking happens...

A short hand notation to create and initialize an array Example: elementType[] arrayRefVar= [value0, value1,....]; Real life example: double[] myList = [1.9, 2.9, 3.4, 3.5];

Array initializer

The new operator is not used in the array initializer syntax. With array initializers you cannot split the code otherwise it will cause an error.

Array initializer Info

"sat"

Array named days has days of the week. The elements are "mon", "tue", "wed", ... "sun". What is days[5]?

Arrays can be used in the same way as a regular variable. myList[2] = myList[0] + myList[1]; This will assign myList[2] the values of myList[0] and myList[1].

Array variables

for(int i = 0; i < myList.length; i++) { myList[i] = 1; }

Array variables for loop

An exception thrown when an invalid array index is used.

Array-Index-Out-Of-Bounds-Exception

If you need to resize an array often, you are better of using an ______ object.

ArrayList

_______ <Students> pupil

ArrayList

The ArrayList class has a toString method that returns a string representing all of the items stored in an ArrayList objec

ArrayList Class's toString method

ArrayList is a class in the Java API that is similar to an array and allows you to store objects. Unlike an array, an ArrayList object's size is automatically adjusted to accommodate the number of items being stored in it - • An ArrayList object automatically expands as items are added to it. - • In addition to adding items to an ArrayList, you can remove items as well. - • An ArrayList object automatically shrinks as items are removed from it. *The ArrayList class is in the java.util package, so the following import statement is required: import java.util.ArrayList;

ArrayList class

Generic class.

ArrayList is a ___ class

Generic class.

ArrayList is a ___ class.

Array is an ordered list of values. Each array has a name by which it can be referenced. Difference between array and arraylist in java include eight points namely Resizable, Performance, Traversal ,Primitives , Length , Type-Safety, Adding elements , Multi-dimensional. 1. Resizable : Array is static in size that is fixed length data structure, One can not change the length after creating the Array object.

ArrayList vs Array: What are differences?

A type parameter. You cannot use primitive types as type parameters in an ArrayList.

ArrayList<BankAccount> What is BankAccount?

A structure that can store many of the same kind of data together at once.

Arrays

- You may create arrays of objects that are instances of classes that you have written. - Objects in an array are accessed with subscripts, just like any other data type in an array.

Arrays of Objects

The process in which a primitive is automatically extracted from a wrapper class object.

Auto-unboxing

The process in which a primitive is automatically converted to a wrapper class object.

Autoboxing

- Its only requirement is that the values in the array must be sorted in ascending order. - Instead of testing the array's first element, this algorithm starts with the element in the middle.

Binary search

- Java performs array bounds checking, which means that it does not allow a statement to use a subscript that is outside the range of valid subscripts for an array. - Bounds checking occurs at runtime. The Java compiler does not display an error message when it processes a statement that uses an invalid subscript. Instead, when the statement executes, the program throws an exception and immediately terminates.

Bounds Checking

A group of related elements that are stores together as a single unit.

Collection

- Because each element of a String array is a String object, you can use an element to call a String method - Because the array's length member is a field, you do not write a set of parentheses after its name. You do write the parentheses after the name of the String class's length method. for (int i = 0; i < names.length; i++) System.out.println(names[i].length());

Calling String methods from an array element

Yes String one = "A"; char one = 'A';

Can a string have just one character? Show an example and show the same answer but with a different variable type.

Yes

Can an array hold strings?

An entire array can be passed as a parameter. Specifically, because an array is an object, a reference to the array is passed to the method. Any changes made to the array elements will be reflected outside of the method.

Can an entire array be passed as a parameter? how is this accomplished?

No, you cannot mix types

Can the same array hold both the name of a student and their grades?

which is the number of items it can store without having to increase its size. - When an ArrayList object is first created, using the no-arg constructor, it has an initial capacity of 10 items. -You can specify a different starting capacity, if you desire, by passing an int argument to the ArrayList constructor. ArrayList<String> list = new ArrayList<String>(100);

Capacity

________ [ ] xyz = new Cars[10]

Cars

1) Define and use arrays for basic data organization. 2) Discuss bounds checking and techniques for managing capacity. 3) Discuss the issues related to arrays as objects and arrays of objects. 4) Explore the use of command-line arguments 5) Describe the syntax and use of variable-length parameter lists. 6) Discuss the creation and use of multidimensional arrays.

Chapter Objectives:

public class Bank { public int count(double atLeast) { int matches = 0; for (BankAccount a : accounts) { if (a.getBalance() >= atLeast) matches++; // Found a match } return matches; } . . . private ArrayList<BankAccount> accounts; }

Counting matches algorithm.

String empty = "";

Create a string that has no characters

String str = "Helllo";

Create a string with the characters, "Hello"

String[] months=new String[12];

Declare an array for the months of the year.

String week[] = {"mon", "tue", "wed", "thu", "fri", "sat", "sun"};

Declare array named week. Elements are mon tue wed thu fri sat sun (in that order).

String phoneNum[] = {"949-234-5678", "714-626-1234"};

Declare array phoneNum. It has 2 elements: 949-234-5678 and 714-626-1234

String[] week = new String[7];

Declare array week. It has 7 elements.

double[] cup=new double[50];

Declare cup array. It has 50 elements like 2, 3.3, 4 cc.

double[] cup={2, 3.3, 4};

Declare cup array. It has elements 2, 3.3, 4 cc.

String[] snack={"gum", "chips"};

Declare snack array. It has elements "gum", "chips".

int x[] = {1.2, 2.4, 3.6, 4.8 };

Declare x array to hold elements are 1.2, 2.4, 3.6, 4.8.

Arrays are objects. Therefore, as with all objects, to create an array we first create a reference to the array (its name). We then instantiate the array itself, which reserves memory space to store the array elements. The only difference between a regular object instantiation and an array instantiation is the bracket syntax.

Describe the process of creating an array. When is memory allocated for the array?

value, element, index

Each ___ (or ____) in an array has a numeric ___.

subscript

Each element of an array is accessed by a number known as a(n)...

This is one of the data items in an array.

Element

int sample[ ]; sample = new int[10]

Even though will typically use one step to declare an array, the creation of an array is a two step process, what are the two steps?

int sample[]; sample = new int[10]

Even though will typically use one step to declare an array, the creation of an array is a two step process, what are the two steps?

int[][][] = { { {0,12,4}, {4,16,5}, {8,20,6}}, {{2,14,7}, {6,18,8}, {10,22,9}} };

Example of hard coding numbers into an array (2x3x2)

starts with a sorted list and cuts in half over and over while making comparisons

Explain how a binary search works

1. use a loop to examine each value 2. compare each value to the min/max so far 3. make the first element the smallest/largest 4. change smallest.largest as necessary

Finding Maximum/Minimum Values

public class Bank { public BankAccount find(int accountNumber) { for (BankAccount a : accounts) { if (a.getAccountNumber() == accountNumber) // Found a match return a; } return null; // No match in the entire array list } . . . }

Finding a value algorithm.

BankAccount largestYet = accounts.get(0); for (int i = 1; i < accounts.size(); i++) { BankAccount a = accounts.get(i); if (a.getBalance() > largestYet.getBalance()) largestYet = a; } return largestYet;

Finding max or min algorithm.

The code to find the highest value in the array is as follows: int highest = numbers[0]; for (int index = 1; index < numbers.length; index++) { if (numbers[index] > highest) highest = numbers[index]; }

Finding the highest value

The following code finds the lowest value in the array int lowest = numbers[0]; for (int index = 1; index < numbers.length; index++) { if (numbers[index] < lowest) lowest = numbers[index]; }

Finding the lowest value

Used for communicating to the compiler the type of data stores in an ArrayList.

Generics

Storing height, weight, and blood pressure

Give an example of a need to use a 3-d array

grades, bus schedule, race times, wind data

Give some examples where you might use arrays

A multidimensional array is implemented in Java as an array of array objects. The arrays that are elements of the outer array could also contain arrays as elements. This nesting process could continue for as many levels as needed.

How are multidimensional arrays implemented in Java?

A Java method can be defined to accept a variable number of parameters by using an ellipsis (...) in the formal parameter list. When several values are passed to the method, they are automatically converted to an array. This allows the method to be written in terms of array processing without forcing the calling method to create the array.

How can Java methods have variable-length parameter lists?

String are immutable, so their contents can't be altered

How can the contents of a string variable be altered?

int d[] = {2,5,7,1,10};

How can you declare and initialize a one-d array called d with the values {2, 5, 7, 1, 10} using one line of code?

y = sentence.indexOf(".") OR ch = sentence.charAt(".");

How can you search for a period in a sentence?

the decimal value is between 65 and 90 inclusive

How can you tell if a character is capitalized?

char sample[] = new char[10]

How do you declare a one-dimensional array to hold ten characters?

arrayListReference.size() - 1

How do you get the last valid index of an ArrayList?

arrayListReference.size() - 1.

How do you get the last valid index of an ArrayList?

It sequentially checks all the values until a match is found.

How does a linear search work?

An array of objects is really an array of object references. The array itself must be instantiated, and the objects that are stored in the array must be created separately.

How is an array of objects created?

Each element in an array can be referenced by its numeric position, called an index, in the array. In Java, all array indexes begin at zero. Square brackets are used to specify the index. For example, nums[5] refers to the sixth element in the array called nums.

How is each element of an array referenced?

4

If an array has 5 elements, what is the index value for the last item in the array?

x = some positive number

If data = "Z", what is the value of x in the expression x = data.compareTo("B") ?

Yes

If you have two arrays, one called apple, and one orange, does this work: apple = orange;

object

In Java, an array is an ___ that must be instantiated.

No. You must use the get method. arrayListReference.get(i)

Is arrayListReference[i] valid to get an element?

size declarator

In an array declaration, this indicates the number of elements that the array will have.

Each array starts with 0 being this as the first item, 1 being this as the second item, and so on.

Index Value

When initializing a two-dimensional array, you enclose each row's initialization list in its own set of braces. int[][] numbers = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };

Initializing a two-dimensional array

- You can read values from the keyboard and store them in an array element just as you can a regular variable. - You can also output the contents of an array element with print and println.

Input and Output array contents

The ArrayList class has an overloaded version of the add method that allows you to add an item at a specific index. nameList.add(1, "Mary");

Inserting an item

references, instantiated

Instantiating an array of objects reserves room to store ____ only. The objects that are stored in each element must be ____ separately.

x.length-1 m>=4

Look at this code. int[] x={ 3, 7, 1, 9, 4, 0, 2 }; int[] y={ 0, 7, 3, 1, 9, 4, 9 }; for(int m=_________; ________; m--) { ........System.out.print(x[ m ] + " and "); ........System.out.println( y[ m ]); } Fill the blank so that it prints 2 and 9 0 and 4 4 and 9

- To pass an array, you pass the value in the variable that references the array. showArray(numbers);

Passing Arrays as Arguments to Methods

When a two-dimensional array is passed to a method, the parameter must be declared as a reference to a two-dimensional array private static void showArray(int[][] array)

Passing two-dimensional arrays to methods

- A sorting algorithm is a technique for scanning through an array and rearranging its contents in some specific order. - The selection sort works like this: The smallest value in the array is located and moved to element 0. Then the next smallest value is located and moved to element 1. This process continues until all of the elements have been placed in their proper order

Selection sort

A sorting algorithm is used to arrange data into some order. A search algorithm is a method of locating a specific item in a larger collection of data. The selection sort and the binary search are popular sorting and searching algorithms.

Selection sort and binary search

A search algorithm is a method of locating a specific item in a larger collection of data. This section discusses the sequential search algorithm, which is a simple technique for searching the contents of an array - The reason -1 is returned when the search value is not found in the array is because -1 is not a valid subscript.

Sequential Search Algorithm

ArrayList <_________> firstName

String

- An array of String objects may be created, but if the array is uninitialized, each String in the array must be created individually. String[] names = { "Bill", "Susan", "Steven", "Jean" }; - In order to use a String object, you must have a reference to the String object.

String Arrays

Declare array of ID numbers. with elements: m94, k34, s72

String ID[] = {"m94", "k34", "s72"};

Concatenates the argument string to the end of this string and returns the new string

String concat(String s)

Replaces all occurrences of oldChar in this String with newChar

String replace(char oldChar, char newChar)

S o d a

String str="Soda"; for (int h = 0; h < str.length(); h++) { ....System.out.print( str[ h ] + " "); }

Returns a substring from beginIndex to endIndex - 1. endIndex can be left blank

String substring(int beginIndex, int endIndex)

ArrayList<type> reference = new ArrayList<type>();

Syntax for constructing an ArrayList?

for (Type variable : collection) statement Example: for (double e : data) sum = sum + e;

Syntax of a for-each loop.

True

T/F - A two-dimensional array has multiple length fields.

True

T/F - An ArrayList automatically expands in size to accommodate the items stored in it.

False

T/F - An array's size declarator can be a negative integer expression.

True

T/F - Both of the following declarations are legal and equivalent: int[] numbers; int numbers[];

True

T/F - Java does not allow a statement to use a subscript that is outside the range of valid subscripts for an array.

True

T/F - The Java compiler does not display an error message when it processes a statement that uses an invalid subscript.

False

T/F - The first size declarator in the declaration of a two-dimensional array represents the number of columns. The second size declarator represents the number of rows.

True

T/F - The subscript of the last element in a single-dimensional array is one less than the total number of elements in the array.

True

T/F - The values in an initialization list are stored in the array in the order that they appear in the list.

True

T/F - When an array is passed to a method, the method has access to the original array.

This operator allocates space for the number of elements indicated in brackets.

The "NEW" operator

- simplifies array processing. for (dataType elementVariable : array) statement; - The enhanced for loop is designed to iterate once for every element in an array

The Enhanced for Loop

0

The first subscript in an array is always...

1 less than the number of elements

The last subscript in an array is always...

A two-dimensional array, however, has multiple length fields. It has a length field that holds the number of rows, and then each row has a length field that holds the number of columns

The length field in a two-dimensional array

length

This array field holds the number of elements that the array has.

N/2

This is the typical number of comparisons performed by the sequential search on an array of N elements (assuming the search values are consistently found).

binary search

This search algorithm repeatedly divides the portion of an array being searched in half.

sequential search

This search algorithm steps through an array, comparing each item with the search value.

remove

To delete an item from an ArrayList object, you use this method.

size

To determine the number of items stored in an ArrayList object, you use this method.

add

To insert an item at a specific location in an ArrayList object, you use this method.

- A two-dimensional array is an array of arrays. It can be thought of as having rows and columns - 2D arrays, can hold multiple sets of data - To declare a two-dimensional array, two sets of brackets and two size declarators are required: The first one is for the number of rows and the second one is for the number of columns double[][] scores = new double[3][4]; - To access one of the elements in a two-dimensional array, you must use both subscripts scores[2][1] = 95;

Two-Dimensional Arrays

The part of an ArrayList statement that informs the compiler of what type of objects the ArrayList can contain. For example, <String>.

Type Parameter

The sixteen-bit digital code used to represent every letter and symbol.

Unicode

two, rare

Using an array with more than ___ dimensions is ____ in an object-oriented system.

variable-length argument lists, which makes it possible to write a method that takes a variable number of arguments

Variable-Length Argument Lists

Called the remove method. Removes the element at position i, moves all elements after the removed element down by one position, and reduces the size of the array list by 1.

What does this do? arrayListReference.remove(i);

1. collecting stats 2. representing the state of a game

array uses

easily manipulated, sorted easily, tallied easily, searched easily

What are some advantages of using arrays to hold data?

Objects

What are strings in Java?

Linear, and Binary

What are the two ways to search a data set?

An array initializer list is used in the declaration of an array to set up the initial values of its elements. An initializer list instantiates the array object, so the new operator is not needed.

What does an array initializer list accomplish?

The enhanced for loop traverses all elements of a collection. You can't assign values with a for each loop.

What does an enhanced for loop (for each) do?

returns the o

What does ch = data.charAt(0) return?

It returns true if there is a match. The variable "y" is boolean

What does the following do, y = test.equals("sup"), and what type of variable is y?

Called the add method. Adds object a at index i and moves all elements by one position, from the current element at position i to the last element in the array list. After each call to the add method, the size of the array list increases by 1.

What does this do? arrayListReference.add(i, a);

Called the add method. Adds an object to the end of the array list and increases the size.

What does this do? arrayListReference.add(object);

// Open the file. PrintWriter outputFile = new PrintWriter("Values.txt"); // Write the array elements to the file. for (int index = 0; index < numbers.length; index++) outputFile.println(numbers[index]); // Close the file. outputFile.close();

Write the contents of each element of the numbers array to a file

xyz[76] =-1;

You have an array of 77 whole numbers named xyz. Assign -1 to the last element in xyz .

*CHALLENGE* What is the output? Use underscore ( _ ) to mimic space.

____6.33

bounds checking

_____ ____ ensures that an index used to refer to an array element is in range.

Command-line, String objects, main

______ -___ arguments are stored in an array of ___ ___ and are passed to the __ method.

the range of valid indexes is 0 to scores.length -1;

accessing an array, we must use valid index. The valid index of an array named scores is what?

A variable used to accumulate results during a traversal.

accumulator

A variable that refers to the same object as another variable.

alias

An array without name is known as ______ ______ in java. As the array do not have any name so it can be used only once. _______ _____ is passed as an argument of method. _____ _____ is created and initialized in the same line.

anonymous arrays

double[] dailyMiles; dailyMiles = new double {170.3, 278.9, 283.2, 158.0, 433.3};

anonymous arrays syntax

the instantiation of an array creates an ______ __ ______ that holds the elements of the array

area of memory

A collection of values, where all the values have the same type, and each value is identified by an index.

array

A programming language construct used to organized objects into an indexed list.

array

a data structure that stores a sequence of values of the same type

array

A value stored in an array.

array element

what error will you get is you try to access an element less than zero?

array index out of bounds exception -1

candy[ candy.length-1 ] ="fruit roll";

candy is an array. Set the last item to "fruit roll".

the variable in a for each loop must be the type of the elements in the ________

collection

A java program receives its ______ _______ arguments in an array.

command line

Data provided on the command line when program is executed. Java stores these in the String array passed into the main method.

command-line argument

second check for if arrays are the same

compare each element

Joins two or more arrays, and returns a copy of the joined arrays

concat()

you may ______ a python list, but not an array

concatenate

A flag variable, in its simplest form, is a variable you define to have one value until some condition is true, in which case you change the variable's value. It is a variable you can use to control the flow of a function or statement, allowing you to check for certain conditions while your function progresses.

flag variable

what two things do you need to compare two arrays?

flag variable and a for loop

Since the elements are indexed starting at 0 and going to arrayName.length - 1, we can print all the elements of an array using a ___ loop:

for

1 2 4 8 16

for (int d = 1; d <= 20; d = d * 2) what are the values of d?

-2 -1 0 1

for (int i = -2; i < 2; i++) what are the values of i?

5 4 3

for (int k = 5; k > 0; k--) { ....if( k<3 ) ....{ ........break; ....} ....System.out.print(k + " "); }

5 4 3 2 1 0

for (int k = 5; k >= 0; k--) what are the values of k?

0 2 4 6 8

for (int m = 0; m <= 9; m = m + 2) what are the values of m?

4 5 6 7 8 9

for (int m = 0; m <= 9; m++) { . . . . if( m<4 ) . . . . { . . . . . . . .continue; . . . . } . . . .System.out.print(m + " "); }

infinite loop

for (int p = 0; p != 9; p = p + 2) what are the values of p?

for (variable : collection) {statement}

for each loop syntax

Calls a function for each array element

forEach()

declare array of to friends called xyz

friends[ ] xyz = new friends[10]

the index of an array must evaluate to an int that is ___ __ ___ __ ___ to work

greater than or equal to 0

snack is an array. It has more than 50 items. Set howMany = the number of items in snack.

howMany=snack.length;

what holds all the java array methods

java.util.Arrays

Joins all elements of an array into a string

join()

Creates a new array with the result of calling a function for each array element

map()

The String compareTo method returns a ____ number if words[i] < largest, _ if they are equal (having the same value), and a_____ number if words[i] > largest

negative, 0, positive

ArrayList<String> areaItems = ________

new ArrayList<String>()

does quick sort create a new array?

no

when specifically instantiating an array, is the new keyword used?

no

If <length> is shorter than the length of the source array, _____ the first elements of that array are copied.

only

arrays are

objects

An error in which an array index does not process the correct range of values, usually resulting in one less element being processed or an attempt being made to process one more element.

off-by-one error

arrays are one of the ____ and ____ __ _data structure in cs

oldest, most basic

declaration and instantiation can be done in ___ step

one

An array with one indexed dimension; a simple list of values.

one-dimensional array

a python list can have elements of many types but an array must have the

same type

A traversal pattern used to find a particular element of an array.

search

ssh

see slide 9 for a basic array example and slide 10 for a diagram showing what happens.

What would you change to find the smallest instead of the largest?

the inequality

what counts the number of elements inside the brackets and uses that as the size of the array?

the java compiler

the area of memory, created by the instantiation of the array, has one name

the name of the array

int[] z

this finds the smallest integer in array z public int smallestInt(_______ _________) { ....int small; ........ ........ ........ ....return small; }

int[] primes = new int[] { 2, 3, 5, 7, 11 };

Initialize an integer array named primes with five values.

it's easily manipulated, sorted easily, tallied easily, searched easily

List two advantages of storing data with arrays

String str = new String("Hello"); String str = "Helllo";

List two ways to construct a string.

Linear and Binary

List two ways to search a data set

After an array variable is declared, you can create an array by using the new operator and assign its reference to the variable with the following syntax. //Syntax is below arrayRefVar = new elementType[arraySize]; The statement does two things. 1- It creates an array using new elementType[arraySize]; 2-It assigns the reference of the newly created array to the variable arrayRefVar.

Referencing an array

//Preferred syntax double[] myList; //This syntax is allowed but not preferred. //This syntax comes from the programming language C/C++ double myList[];

The proper syntax to declare an array in Java

Two different arrays that should be combined into one array containing objects.

What are parallel arrays?

objects

What are strings in Java? objects, arrays, or characters?

index

What describes the position of an element within an array?

Use the System.arraycopy method to copy elements from one array to another.

What does System.arraycopy do?

An array variable stores a reference to the array. Copying the variable yields a second reference to the same array.

What does an array variable do?

Returns the o

What does ch = data.charAt(0) in the string "open now." return?

return true if match, the variable y is boolean

What does the following do, y = test.equals("sup"), and what type of variable is y?

Removes an element at position i.

What does this do? System.arraycopy(data, i + 1, data, i, data.length - i - 1);

Adds a new element at position i into data, first moves all elements from i onward one position up. Then inserts the new value. Last element is lost.

What does this do? System.arraycopy(data, i, data, i + 1, data.length - i - 1); data[i] = x;

Once an array is created it's size is fixed. An array reference variable is used to access the elements in an array using index.

Array Info.

arrayRefVar[index] = value; For example: myList[0] = 5.6; myList[1] = 4.5; ......... myList[9] = 98.13

Assign values to array elements

String one = "A"; char one = 'A';

Can a string have just one character? Show an example

yes

Can an array hold strings?

No mixing

Can the same array hold both the name of a student and their grades?

String numbers[][] = { {"Tom", "555-3322"}, {"Sam", "555-8976"}. {"Cole", "596-2142"} };

Create an appropriate array to hold the names and phone numbers of 3 people.

String data[] = {"This", "is", "great"};

Create and fill an array with the strings "This", "is" "great"

When you declare an array in Java the array variable does not allocate any space in memory for the array. It only creates a storage location for the reference to the array. If a variable does not contain a reference to the array the variable is null. You can not assign elements to an array unless it has already been declared.

Creating Arrays

Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement as shown below .//This syntax is preferred elementType [] arrayRefVar = new elementType[arraySize]; Here is an example: double [] myList = new double[10]; The statement declares an array variable myList, creates an array of 10 elements of double type, and assigns its reference to myList.

Declaring an array variable

An array is a sequence of values of the same type. They can hold both primitives and objects.

Definition of an array

compares values at two index locations and does a swap if necessary, it repeats this over and over, need two loops

Explain what a Bubble sort is and how does it word? How many loop do you need?

An integer value used to specify the position of an element in an array. The array index is an int value starting with the value 0 for the first element. 1 for the second, and so on.

Index

What is the output?

1 2 3 4 5

What is the output?

16

What is the output?

3.0 4.5 1.0 2.5 5.0 3.0 2.0 3.0

What is the output?

4.5 5.0

What is the output?

42.0

What is the output?

5

recording height, weight, blood pressure

Give an example of a need to use a 3-d array.

Grades, bus schedule, race times, wind data

Give three examples where you might use arrays

Methods

How are arrays implemented?

string are immutable, contents can't be altered

How can the contents of a string variable be altered?

int d[ ] = {2,5,7,1,10};

How can you declare and initialize a one-d array called d with the values {2, 5, 7, 1, 10} using one line of code?

y = sentence.indexOf("."), ch = sentence.charAt(".");

How can you search for a period in a sentence?

the decimal value is between 65 and 90 inclusive (I think this is referring to the ascii chart)

How can you tell if a character is capitalized?

arrayReference[length - 1]

How do you access the last index of an array?

Use the clone method to copy the elements of an array. Has a return type of Object.

How do you copy the elements of an array?

char sample[ ] = new char [10];

How do you declare a one-dimensional array to hold ten characters?

2

How many loops are necessary in the Bubble sort routine?

for (int i = 0; i < ROWS; i++) for (int j = 0; j < COLUMNS; j++) board[i][j] = " ";

How to fill or search a 2D array.

double[] newData = new double[2 * data.length]; System.arraycopy(data, 0, newData, 0, data.length); data = newData;

How to grow an array that has run out of space.

4 (it starts at 0)

If an array has 5 elements, what is the index value for the last item in the array?

x =7, y = 4, z = 2

If x = bus.length, and y = bus[0].length, z = bus[1].length, what are the values for x , y, and z?

Yes

If you have two arrays, one called apple, and one orange, does this work: apple = orange:;

part would be a string and in this case ken

Suppose data is the string "Broken" What is the value of part in the expression part =data.substring(3,6)? What type of variable is part?

Returns the character

Suppose data is the string "open now." What does ch = data.charAt(8) return?

false all the characters must match

Suppose the test is the string supal, what value does y have?

50

Suppose you are thinking of a number in a binary sort from 0 to 100, what is the first number that it's compared to?

all values at the various positions of num1 match num2, you are causing num1 to reference num2

Suppose you have two arrays num1 and num2. What does num1 = num2 do?

arrayReference[index] Ex. data[2]

Syntax for array element access

final int ROWS = 3; final int COLUMNS = 3; String[][] board = new String [ROWS][COLUMNS];

Syntax for creating an array with 3 rows and 3 columns.

typeName[] arrayReference = new typeName[length] Ex. double[] data = new double[10];

Syntax for initializing an array

System.arraycopy(from, fromStart, to, toStart, count);

Syntax of System.arraycopy method.

double[] prices = (double[]) data.clone();

Syntax of copying an array.

an array that has a diff num of columns for each row int bus[][] = new int[7][]; bus[0] = new int[4]; //on Mondays you can hold 4 data pts bus[1] = new int[2]; // on Tuesday, 2 data pts bus[2] = new int[4]; and so on

What is an irregular array and give an example of declaring one called bus for a bus schedule that just runs M, W, F for 4 times each day, on Tues, Thurs, and Sat twice, and Sun once.

int temp = new int[3];

What single line of code can be used to declare a one D array called temp to hold 3 items?

two dimension [22][2] in this case the row is the student number, if you had 22 in the class

What type of an array would you use to hold the weight and height of students in the class of 2010?

int g[][][] = new int[3][2][4]; this is a 3 dimensional array

What type of array would you use to hold all of your final exam grades (assume just 1st and 2nd semester) for all of your high school years. Write a piece of code to declare it.

5

What would x = d.length give for the value of x? d[ ] = {2,5,7,1,10};

Binary

Which way can be used if the data is organized?

Linear

Which way can be used if the data is unorganized?

they group together related data, they organize data, they assist in the sorting and searching of data

Why are arrays convenient?

int min = 10000; for (int i=0; i< 10; i++) if (sample[i] < min) min = sample[i];

Write a method to find the minimum value in a one dimensional array.

for (int d=0; d< 2; d++) for (int c=0; c< 3; c++) for (int r=0; r<2; r++) g[r][c][d] = n; n = n + 2;

Write a piece of code to initial an array called g that's 2x3x2 to even numbers starting with zero. n=0;

for (int i=0; i<5; i++) sample[i] = 10;

Write a piece of code to initialize the five elements of a one-d array to the int value of 10.


Set pelajaran terkait

Critical Reading + Writing Written Assignment

View Set

Taylor: Fundamentals of Nursing, Ninth Edition - Chapter one quiz

View Set

Illinois Statutes and Regulations Pertinent to Accident & Health Only

View Set

CHPT 18: Ad, PR and Sales Promotions

View Set