CSE 143 - CSE 143 Lecture 1 Arrays(review slides created by...

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

View Full Document Right Arrow Icon

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

View Full Document Right Arrow Icon

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

View Full Document Right Arrow Icon

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

View Full Document Right Arrow Icon

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

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: CSE 143 Lecture 1 Arrays (review) slides created by Marty Stepp http://www.cs.washington.edu/143/ 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. i n d e x 1 2 3 4 5 6 7 8 9 v a l u e 12 49-2 26 5 17-6 84 72 3 element 0 element 4 element 9 3 Array declaration type name = new type [ length ]; – Example: int numbers = new int[10]; – All elements' values are initially 0. i n d e x 1 2 3 4 5 6 7 8 9 v a l u e 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"); } i n d e x 1 2 3 4 5 6 7 8 9 v a l u e i n d e x 1 2 3 4 5 6 7 8 9 v a l u e 27-6 5 Out-of-bounds • Legal indexes: between 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 i n d e x 1 2 3 4 5 6 7 8 9 v a l u e 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() . 7 Quick initialization...
View Full Document

{[ snackBarMessage ]}

Page1 / 17

CSE 143 - CSE 143 Lecture 1 Arrays(review slides created by...

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