01-review - CSE 143 Lecture 1 Review: Arrays and objects...

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

View Full Document Right Arrow Icon
1 CSE 143 Lecture 1 Review: Arrays and objects slides created by Marty Stepp and Ethan Apter 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. 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 1

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

View Full DocumentRight Arrow Icon
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 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("Element 3 is negative"); } 27 0 0 -6 0 0 0 0 0 0
Background image of page 2
3 5 Out-of-bounds • Legal indexes: between 0 and the array's length - 1 . – Accessing 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 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 – NOTE: It does not use parentheses like a String's .length() . 0 2 4 6 8 10 12 14
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 7 Quick initialization type [] name = { value , value , value }; – Example: int[] numbers = {12, 49, -2, 26, 5, 17, -6}; – Useful when you know what the array's elements will be. – The compiler figures out the size of the array. index 0 1 2 3 4 5 6 value 12 49 -2 26 5 17 -6 8 Array as parameter public static type methodName ( type [] name ) { – Example: public static double average( int[] numbers ) { ...
Background image of page 4
Image of page 5
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 09/29/2010 for the course CSE 143 taught by Professor Sr during the Spring '08 term at University of Washington.

Page1 / 13

01-review - CSE 143 Lecture 1 Review: Arrays and objects...

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

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