Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

Arrays.
Chapter 41 Variables and JSP Control Structures JavaServer Pages By Xue Bai.
Arrays, A1 COMP 401, Fall 2014 Lecture 4 8/28/2014.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
Chapter 10 Introduction to Arrays
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Arrays.
Computer Science A 10: 20/3. Array Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[] double[]
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
Datalogi A 8: 27/10. Array Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[] double[] data.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
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.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
Chapter 9: Arrays and Strings
Chapter 9 Introduction to Arrays
Chapter 10 2D Arrays Collection Classes. Topics Arrays with more than one dimension Java Collections API ArrayList Map.
CS0007: Introduction to Computer Programming Introduction to Arrays.
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 Arrays in Java Corresponds with Chapter 6 of textbook.
Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword.
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.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 9 Multidimensional Arrays and the ArrayList Class.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Introduction to Collections Arrays. Collections Collections allow us to treat a group of values as one collective entity. The array is a collection of.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
15440 Distributed Systems Recitation 1 Objected-Oriented Java Programming.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
Introduction to Java Java Translation Program Structure
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
 2007 Pearson Education, Inc. All rights reserved C Arrays.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
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.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
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.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Windows Programming Lecture 03. Pointers and Arrays.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Arrays, For loop While loop Do while loop
Can store many of the same kind of data together
Object Oriented Programming in java
MSIS 655 Advanced Business Applications Programming
OBJECT ORIENTED PROGRAMMING II LECTURE 13_2 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
Java Programming Language
Arrays.
Presentation transcript:

Arrays BCIS 3680 Enterprise Programming

Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to elements  Using arrays with for loops  Using arrays in methods  HashMap  Strings  Dealing with one character  Dealing with multiple characters

Array 3  An array is a collective of variables of the same data type.  The data type can be:  Primitive types, e.g., int, long, double, float, etc.  Class  Java classes, e.g., String  Classes you build

Array Terminology  Each variable in the array is called an element.  The size (or length ) of the array is the number of the elements in the array.  This number cannot be changed once an array is declared and instantiated.  The position of the element in the array is called the index (or subscript ) of the element.  The index must be an int (or char, byte, short ). 4

Array Terminology 5

 You refer to an element in an array by specifying: arrayName[index] cdTracks[2] // Third track on CD  The indexes are 0-based.  The index for the first element is 0. cdTracks[0]  The index for the last element is (size-1). cdTracks[15] // If CD has 16 tracks  If you try to access an index that is greater than (size-1), Java throws an ArrayIndexOutOfBoundsException.  This error is not detected at compile time but thrown at run time. 6

Creating an Array  In Java, arrays are implemented as objects.  Creating an array thus is similar to creating other objects.  Declare the reference variable for the array.  Instantiating the array.  Declaring an array: DataType[] arrayName; String[] cdTracks; double[] bcis3680Grades;  Declaring an array does not actually create the array.  Note that the size of the array is not defined yet. 7

Instantiating an Array  Instantiating an array (and specifying size of the array): arrayName = new DataType[Size]; cdTracks = new String[16]; bcis3680Grades = new double[28];  Note that there are no brackets on the left side.  Alternatively, you may combine declaration and instantiation: Datatype[] arrayName = new Datatype[Size]; String[] cdTracks = new String[16]; double[] bcis3680Grades = new double[28]; 8

Default Initial Values of Elements  When we instantiate an array, the elements are given initial values automatically, until we assign specific values to them explicitly. Element Data TypeInitial Value byte, short, int, long 0 float, double 0.0 charSpace character boolean false String null Object null 9

A Shortcut  Arrays can be instantiated by specifying a list of initial values. datatype[] arrayName = {value0,value1,…}; where valueN is an expression evaluating to the data type of the array and is the value to assign to the element at index N. int[] oddNumbers = { 1, 3, 5, 7, 9, 11 }; // This statement does three things all at once // 1. declares a float array testScores; // 2. instantiates it (implicitly); and // 3. assigns values to the elements. float[] testScores = {92.0f, 87.5f, 95.0f}; 10

Assigning Initial Values to Elements 11  We may specify to which array element we want to assign a value by using its index number. cdTracks[0] = "White Christmas";  The same syntax is used when we want to access the value stored in that element later. System.out.println("Title: " + cdTracks[0]); ElementSyntax Element 0 arrayName[0] Element i arrayName[i] Last element arrayName[arrayName.length - 1]

Index Can Be…  A literal carMSRPs[3] = ;  Value of a variable carMSRPs[i] = ;  Value returned by a called method carMSRPs[getNextIndex()] = ;  Other expressions carMSRPs[carMSRPs.length-1] = ; carMSRPs[carMSRPs.length-2] = ; 12

Assigning Initial Values to Elements  We may assign the values to each element one by one. cdTracks[0] = "White Christmas"; cdTracks[1] = "Have Yourself a Merry Little Christmas"; … studentScores[0] = 92.0f; studentScores[1] = 87.5f; studentScores[2] = 95.0f; …  What if we have 100 elements to assign?  It’s helpful what we enter between the brackets does not have to be a literal int all the time. As long as it’s an expression that will evaluate to an integer value before the element is accessed, that’s fine. 13

Using for Loop with Arrays 14  A for loop works very well with an array because: Characteristic of ArrayHow It Can Be Handled by for Loop Composed by elements that are of identical data type. Thus statements written for one element can be repeated for all other elements. Putting those statements inside the loop body allows them to be repeated for all elements. Array length is a fixed number. We know exactly how many times those statements will be run: the length of the array. A for loop is the most proper loop to use when the number of iterations can be determined ahead of time. Array index is an integer starting with 0.If we initialize the loop control variable to 0, it will match up with the array indexes. The last array element index is length-1.If we set the loop condition as i<length and updates i by i++, the last iteration is run when the value of i reaches length -1.

Using for Loop with An Array for( int i = 0; i < someArray.length; i++ ) { // code for working on the element someArray[i] } Iteration No. Array Element Being Worked on Value of i Expression to Access Array Element Value of i after Iteration 1 Element # 10 someArray[ 0 ] 1 2 Element # 21 someArray[ 1 ] 2 3 Element # 32 someArray[ 2 ] 3 … assuming someArray.length is Element # 109 someArray[ 9 ] 10 (loop ends) 15

Using Array in Methods  An array can be used as:  a parameter to a method  the return value from a method  a local variable in a method  Brackets are included in the method header (where the data types of parameters are defined).  Brackets are not included in method calls (where the data itself is passed). 16

Array as Parameter/Argument  To define a method that takes an array as a parameter, use brackets in the parameter data type to indicate that an array will be passed into this method: accessModifier returnType methodName( dataType[] arrayName )  To pass an array as an argument when calling a method, use the array name without brackets: methodName( arrayName )  No brackets are needed when passing an array name as an argument. 17

Array as Return Value 18  To define a method that returns an array, use this syntax: accessModifier DataType[] methodName( paramList)  Note the brackets in the return type to indicate that an array will be returned.  To use an array as the return value,  First, declare an array variable of the same type (note the brackets that indicate this variable being an array): DataType[] newArray;  Then, assign the array returned from the method call to this newly declared array (note there are no brackets on the left side): newArray = methodName();  Finally, you can access elements in this array like usual: DataType oneVar = newArray[0];

ArrayList 19  Unlike arrays, an ArrayList object does not have a set size.  It automatically expands as new elements are added and shrinks as elements are removed.  Must import the ArrayList class from the java.util package to use ArrayList.  Creating an ArrayList: ArrayList listName = new ArrayList ();  Use add( ) to store values into the ArrayList.  Use get( ) to retrieve the value of the element as identified by the index.

HashMap 20  A two-dimensional structure.  Each element contains a “key” and a “value”.  The contents stored in the key “column” and those in the value “column” may be of different types.  For both, it can be any object that is a subclass of Object. But typically String is used.  Must import the HushMap class from the java.util package.  Creating a HashMap: HashMap mapName = HashMap ();  Use put(, ) to store key-value pairs into the map.  Use get( ) to retrieve the value corresponding to the key.

A Sneak Peek into Strings 21  Each character in a string can be located by its position number (index) in the string. This index works much like the index in an array. It starts at 0; each refers to an “element” (a character); and all the “elements” are of the same data type (char).  The index for the last character in a string is one less the length of the string, e.g., aString.length()–1.  Notice that for strings, you find their length by calling the length() method whereas for arrays, length is a property. Return typeSignature intlength() Returns the number of characters in the string.

String Terminology 22

Dealing with A Character in String 23 You Know AlreadyYou Want to KnowThen Use… A character in the stringWhere it first appears in the string indexOf() A character in the stringWhere it last appears in the string lastIndexOf() A position in the stringWhich character is in that position* charAt()  * You don’t access the “element” by writing aString[index]. Instead, call the charAt() method and pass the index for the character as the argument, e.g., aString.charAt(0).

Dealing with A Character in String Return typeSignature charcharAt( int index ) Returns the character at that particular position specified by index. intindexOf( char ch ) Finds the location of the first occurrence of the character as indicated by the parameter ch. If the string does not contain ch, return value is -1. intlastIndexOf( char ch ) Finds the location of the last occurrence of the character as indicated by the parameter ch. If the string does not contain ch, return value is

Dealing with Multiple Characters  Often, we need to extract part of a string (a “substring”) and save the result as another string for further processing.  Use the substring() method.  We need to specify where to start to cut and where to stop to get the part we want.  If we are starting at the very beginning (index is 0) or at a fixed location every time (index is x), then that’s easy.  However, if we won’t be able to tell where the starting character will appear until the program is run, we need to first look up the index of that character.  Use the indexOf() method.  If we will start with the last occurrence of the character, then use the lastIndexOf() method. 25

Dealing with Multiple Characters 26 Return typeSignature Stringsubstring( int startPos ) Extracts a part that begins at the index indicated by the int parameter and ends at the last character in the calling string. Stringsubstring( int startPos, int endPos ) Extracts a part that begins at the index indicated by the first int parameter and ends at the character whose index is endPos–1.* * The starting position is inclusive, i.e., the character in the position indicated by the first parameter is part of the returned substring. In contrast, the ending position is exclusive.

Extracting a Substring 27