01-array - CSE143 Lecture1 Arrays(review)...

Info iconThis preview shows pages 1–8. Sign up to view the full content.

View Full Document Right Arrow Icon
CSE 143 Lecture 1 Arrays (review) slides created by Marty Stepp http://www.cs.washington.edu/143/
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
2 Arrays (7.1) array : An object that stores many values of the same type. element : One value in an array. index : A 0-based integer to access an element from an array. index 0 1 2 3 4 5 6 7 8 9 value 12 49 -2 26 5 17 -6 84 72 3 element 0 element 4 element 9
Background image of page 2
3 Array declaration type [] name = new type [ length ]; Example: int[] numbers = new int[10]; All elements' values are initially 0. index 0 1 2 3 4 5 6 7 8 9 value 0 0 0 0 0 0 0 0 0 0
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
4 Accessing elements name [ index ] // access name [ index ] = value ; // modify Example: numbers[0] = 27 ; numbers[3] = -6 ; System.out.println( numbers[0] ); if ( numbers[3] < 0) { System.out.println("value 3 is negative"); } index 0 1 2 3 4 5 6 7 8 9 value 27 0 0 -6 0 0 0 0 0 0
Background image of page 4
5 Out-of-bounds Legal indexes: between  0  and the  array's length - 1 . Reading or writing any index outside this range will throw an  ArrayIndexOutOfBoundsException . Example: int[] data = new int[10]; System.out.println(data[0]); // okay System.out.println(data[9]); // okay System.out.println(data[-1]); // exception System.out.println(data[10]); // exception index 0 1 2 3 4 5 6 7 8 9 value 0 0 0 0 0 0 0 0 0 0
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
6 The  length  field name .length An array's  length  field stores its number of elements. for (int i = 0; i < numbers.length ; i++) { System.out.print(numbers[i] + " "); } // output: 0 2 4 6 8 10 12 14 It does not use parentheses like a String's  .length() .
Background image of page 6
7 Quick initialization type [] name = { value , value ,  …  value }; Example: int[] numbers = {12, 49, -2, 26, 5, 17, -6};
Background image of page 7

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 8
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 17

01-array - CSE143 Lecture1 Arrays(review)...

This preview shows document pages 1 - 8. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online