Java – An Object Oriented Language CS 307 Lecture Notes Lecture Weeks 5-6 Khalid Siddiqui.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Arrays.
Arrays, A1 COMP 401, Fall 2014 Lecture 4 8/28/2014.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Lecture 05 - Arrays. Introduction useful and powerful aggregate data structure Arrays allow us to store arbitrary sized sequences of primitive values.
Programming with Collections Collections in Java Using Arrays Week 9.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
ECE122 L13: Arrays of Objects March 15, 2007 ECE 122 Engineering Problem Solving with Java Lecture 13 Arrays of Objects.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Arrays. A problem with simple variables One variable holds one value –The value may change over time, but at any given time, a variable holds a single.
Chapter 9: Arrays and Strings
Chapter 8 Arrays and Strings
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Java Unit 9: Arrays Declaring and Processing Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Introduction to Java Subject Code CSE-404E. Welcome to the First class of Session Jan 2007-April 2007.
A First Book of ANSI C Fourth Edition
Chapter 8 Arrays and Strings
Arrays Part 9 dbg. Arrays An array is a fixed number of contiguous memory locations, all containing data of the same type, identified by one variable.
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Chapter 8: Arrays.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Review of ICS 102. Lecture Objectives To review the major topics covered in ICS 102 course Refresh the memory and get ready for the new adventure of ICS.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
Pointers *, &, array similarities, functions, sizeof.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
CSCI 3328 Object Oriented Programming in C# Chapter 7: Arrays 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX 78539
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays.
Chapter 8: Part 3 Collections and Two-dimensional arrays.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
int [] scores = new int [10];
Scis.regis.edu ● CS-362: Data Structures Week 6 Part 2 Dr. Jesús Borrego 1.
Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
02/09/2005 Introduction to Programming with Java, for Beginners Arrays (of primitives)
1 ENERGY 211 / CME 211 Lecture 4 September 29, 2008.
© 2004 Pearson Addison-Wesley. All rights reserved7-1 Array review Array of primitives int [] count; count = new int[10]; Array of objects Grade [] cs239;
Lecture #15 ARRAYS By Shahid Naseem (Lecturer). 2 ARRAYS DEFINITION An array is a sequence of objects of same data type. The objects in an array are also.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
Introduction to programming in java Lecture 21 Arrays – Part 1.
Windows Programming Lecture 03. Pointers and Arrays.
Array in C# Array in C# RIHS Arshad Khan
Arrays, 2-D Arrays, and ArrayList
Objects First with Java CITS1001
Topics Covered: Arrays, 1-D & 2-D Passing & Returning Arrays
Arrays .
Arrays ICS2O.
Suggested self-checks: Section 7.11 #1-11
CS1001 Lecture 14.
How do you do the following?
Presentation transcript:

Java – An Object Oriented Language CS 307 Lecture Notes Lecture Weeks 5-6 Khalid Siddiqui

Objectives: Learn about arrays and when to use them Learn the syntax for declaring and initializing arrays Learn how to access array’s size and elements Understand two-dimensional arrays

What is an Array An array is a block of consecutive memory locations of the same data type. Individual locations are called array’s elements. Sometimes when we say “array’s element” we mean the value stored in that element An array of doubles

What is an Array (cont’d) Rather than treating each element as a separate named variable, the whole array gets one name. Specific array elements are referred to by using array’s name and the element’s number, called index or subscript. c[0]c[1]c[2]c[3] c is array’s name

Indices (Subscripts) In Java, an index is written within square brackets following array’s name (e.g., a[k]). Indices start from 0; the first element of an array a is referred to as a[0] and the n-th element as a[n-1]. An index can have any int value from 0 to array’s length - 1.

Indices (cont’d) We can use an int variable or any expression that evaluates to an int value as an index: a [3] a [k] a [k - 2] a [ (int) (6 * Math.random()) ]

Indices (cont’d) In Java, an array is declared with fixed length that cannot be changed. Java interpreter checks the values of indices at run time and throws IndexOutOfBoundsException if an index is negative or if it is greater than the length of the array - 1.

Why Do We Need Arrays? The power of arrays comes from the fact that the value of a subscript can be computed and updated at run time. int sum = 0; sum += score0; sum += score1; … sum += score999; Before (no arrays): int n = 1000; int sum = 0, k; for (k = 0; k < n; k++) sum += scores[k]; After (with arrays): 1000 times!

Why Arrays? (cont’d) Arrays give direct access to any element — no need to scan the array. if (k == 0) display (score0); else if (k == 1) display (score1); else … // etc. Before (no arrays): display (scores[k]); After (with arrays):

Arrays as Objects In Java, an array is an object. If the type of its elements is anyType, the type of the array object is anyType[ ]. There are two ways to declare an array: anyType [ ] arrName; The difference becomes significant only when several variables are declared in one statement: int [ ] a, b; // both a, b are arrays int a [ ], b; // a is an array, b is not anyType arrName [ ]; or

Arrays as Objects (cont’d) As with other objects, the declaration creates only a reference, initially set to null. An array must be created before it can be used. There are two ways to create an array: arrName = new anyType [ length] ; Brackets, not parens! or arrName = new anyType [ ] { val1, val2, …, valN };

Declaration and Initialization When an array is created, space is allocated to hold its elements. If a list of values is not given, the elements get the default values. scores = new int [10] ; // length 10, all values set to 0 words = new String [10000]; // length 10000, all values set to null

Initialization (cont’d) An array can be declared an initialized in one statement: int scores [ ] = new int [10] ; // length 10 private double gasPrices [ ] = { 1.49, 1.69, 1.74 }; String words [ ] = new String [10000]; String cities [ ] = {"Atlanta", "Boston", "Cincinnati" };

Initialization (cont’d) Otherwise, initialization can be postponed until later: String words [ ]; // not yet initialized... words = new String [ console.readInt() ]; private double gasPrices [ ]; // not yet initialized … gasPrices = new double [ ] { 1.52, 1.69, 1.75 };

Array’s Length The length of an array is determined when that array is created. The length is either given explicitly or comes from the length of the {…} initialization list. The length of an array arrName is referred to in the code as arrName.length. length appears like a public field (not a method) in an array object.

Initializing Elements Unless specific values are given in a {…} list, all the elements are initialized to the default value: 0 for numbers, false for booleans, null for objects. If its elements are objects, the array holds references to objects, which are initially set to null. Each object-type element must be initialized before it is used.

Initializing Elements (cont’d) Example 1:... Color pens [ ]; // not yet initialized... pens = new Color [ 3 ]; // array of 3 elements // is created; all the elements are set to null pens [0] = Color.blue; pens [1] = new Color (15, 255, 255); pens [2] = g.getColor(); // Now all 3 elements are initialized

Initializing Elements (cont’d) Example 2: JButton numButtons[ ] = new JButton [10 ]; // Initialize all the elements: for (int d = 0; d < numButtons.length; d++) { numButtons [d] = new JButton(String.valueOf(d)); numButtons [d].addActionListener (this); }

Passing Arrays to Methods As other objects, an array is passed to a method as a reference. The elements of the original array are not copied and are accessible in the method’s code.

Passing to Methods (cont’d) Example: /** * Swaps a [ i ] and a [ j ] */ public void swap (int a[ ], int i, int j) { int temp = a [ i ]; a [ i ] = a [ j ]; a [ j ] = temp; }

Returning Arrays from Methods As for other objects, an array can be returned from a method. The returned array is usually constructed within the method or obtained from calls to other methods. The return type of a method that returns an array with someType elements is designated as someType [ ].

Returning from Methods (cont’d) Example: public double[ ] solveQuadratic (double a, double b, double c) { double d = b * b - 4 * a * c; if (d < 0) return null; d = Math.sqrt(d); double roots[ ] = new double[2]; roots[0] = ( - b - d) / (2*a); roots[1] = ( - b + d) / (2*a); return roots; } Or simply: return new double[ ] { ( - b - d) / (2*a), ( - b + d) / (2*a) };

Two-Dimensional Arrays 2-D arrays are used to represent tables, matrices, game boards, images, etc. An element of a 2-D array is addressed using a pair of indices, “row” and “column.” For example: board [ r ] [ c ] = 'x';

2-D Arrays: Declaration // 2-D array of char with 5 rows, 7 cols: char letterGrid [ ] [ ] = new char [5][7]; // 2-D array of Color with 1024 rows, 768 cols: Color image [ ] [ ] = new Color [1024][768]; // 2-D array of double with 2 rows and 3 cols: double sample [ ] [ ] = { { 0.0, 0.1, 0.2 }, { 1.0, 1.1, 1.2 } };

2-D Arrays in Java In Java, a 2-D array is basically a 1-D array of 1-D arrays, its rows. Each row is stored in a separate block of consecutive memory locations. If m is a 2-D array, then m[k] is a 1-D array, the k-th row. m.length is the number of rows. m[k].length is the length of the k-th row.