Download presentation
Presentation is loading. Please wait.
Published byMilo Cobb Modified over 8 years ago
2
BUILDING JAVA PROGRAMS CHAPTER 7 Arrays
3
days until the AP Computer Science test
4
At the end of this class, you will be able to Explain default values in arrays. Use methods in the Arrays class.
5
Array Initialization int arr = new int[10]; boolean bArr = new boolean[3]; System.out.println(arr[0]); System.out.println(bArr[0]); What is output? 0 false
6
Array Initialization Each element initially gets a default “zero equivalent” value. TypeDefault value int0 double0.0 booleanfalse String (or other object) null (means, "no object")
7
Array Initialization Commonly, we know the values we want to store in an array when it is declared. Example: String[] daysOfTheWeek = new String[7]; daysOfTheWeek[0] = “Sunday”; daysOfTheWeek[1] = “Monday”; daysOfTheWeek[2] = “Tuesday”; daysOfTheWeek[3] = “Wednesday”; daysOfTheWeek[4] = “Thursday”; daysOfTheWeek[5] = “Friday”; daysOfTheWeek[6] = “Saturday”; Lots of code to do something simple.
8
Quick Array Initialization Syntax: type[] name = {,, …, }; The compiler determines the size of the array by counting values. Example: String[] daysOfTheWeek = {“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”}; Syntax Yoda
9
Limitations of arrays You cannot compare arrays with == or equals : int[] a1 = {42, -7, 1, 15}; int[] a2 = {42, -7, 1, 15}; if (a1 == a2) {... } // false! if (a1.equals(a2)) {... } // false! An array does not know how to print itself: int[] a1 = {42, -7, 1, 15}; System.out.println(a1); // [I@98f8c4]
10
The Arrays class Class Arrays in package java.util has useful static methods for manipulating arrays: Syntax: Arrays.methodName(parameters) Method nameDescription binarySearch(array, value) returns the index of the given value in a sorted array (or < 0 if not found) copyOf(array, length) returns a new copy of an array equals(array1, array2) returns true if the two arrays contain same elements in the same order fill(array, value) sets every element to the given value sort(array) arranges the elements into sorted order toString(array) returns a string representing the array, such as "[10, 30, -25, 17]"
11
Arrays.toString Arrays.toString accepts an array as a parameter and returns a String representation of its elements. int[] e = {0, 2, 4, 6, 8}; e[1] = e[3] + e[4]; System.out.println("e is " + Arrays.toString(e)); Output: e is [0, 14, 4, 6, 8] Must import java.util.*;
12
Homework for Chapter 7 HomeworkAssigned onDue on Read BJP 7.1 and write notes11/24/201411/26/2014 Practice It: SC 7.1, 7.2, 7.411/24/201411/26/2014 Practice It: Ex 7.111/24/201411/26/2014 Practice It: SC 7.3, 7.511/25/201411/26/2014 Practice It: Ex 7.211/25/201411/26/2014
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.