Arrays An array is a structure that holds multiple values of the same type. The length of an array is established when the array is created (at runtime).

Slides:



Advertisements
Similar presentations
Arrays.
Advertisements

Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
Array Yoshi. Definition An array is a container object that holds a fixed number of values of a single type. The length of an array is established when.
Introduction to arrays Data in economy size packages.
1 CIS 205 Practice Test George Lamperti A word that has a predefined meaning in a C++ program and cannot be used as a variable name is known as.
ARRAYS public class ArrayDemo { public static void main(String[] args) { int[] anArray; // declare an array of integers anArray = new int[10]; // create.
Arrays. Arrays  When a value is to be used in a program, a variable is declared to hold that value  What about storing the results of exams for a large.
Loops – While, Do, For Repetition Statements Introduction to Arrays
CS 106 Introduction to Computer Science I 10 / 04 / 2006 Instructor: Michael Eckmann.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
Chapter Eight: Arrays 1.Terms and what they mean 2.Types of arrays -One Dimensional arrays -Two Dimensional arrays -ragged arrays -Parallel arrays 3. Methods.
Arrays. Arrays  When a value is to be used in a program, a variable is declared to hold that value  What about storing the results of exams for a large.
CS0007: Introduction to Computer Programming Introduction to Arrays.
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
DAT602 Database Application Development Lecture 5 JAVA Review.
Arrays (Part 1) Computer Science Erwin High School Fall 2014.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
ISBN Chapter 7 Expressions and Assignment Statements.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
Array Processing - 2. Objectives Demonstrate a swap. Demonstrate a linear search of an unsorted array Demonstrate how to search an array for a high value.
Arrays Chapter 7. 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores : Inspecting.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
 2005 Pearson Education, Inc. All rights reserved. 1 Arrays.
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.
Pemrograman Dasar Arrays PTIIK - UB. Arrays  An array is a container object that holds a fixed number of values of a single type.  The length of an.
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.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
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.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.
Primitive data Week 3. Lecture outcomes Primitive data – integer – double – string – char – Float – Long – boolean Declaration Initialisation Assignments.
Arrays Arrays in C++ An array is a data structure which allows a collective name to be given to a group of elements which all have.
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.
August 6, 2009 Data Types, Variables, and Arrays.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
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.
Agenda Comments Identifiers Keywords Syntax and Symentics Indentation Variables Datatype Operator.
Arrays-. An array is a way to hold more than one value at a time. It's like a list of items.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
CS 180 Recitation 7 Arrays. Used to store similar values or objects. An array is an indexed collection of data values of the same type. Arrays are the.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
Array and String.
Array contiguous memory locations that have the same name and type. Note: an array may contain primitive data BUT an array is a data structure a collection.
02/09/2005 Introduction to Programming with Java, for Beginners Arrays (of primitives)
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
Java Programming Language Lecture27- An Introduction.
(Java Looping and Conditional Statements). Flow of control Sequential Executes instructions in order Method Calls Transfer control to the methods, then.
Arrays Chapter 7.
Java Arrays. Array Object An array :a container object holds a fixed number of values of a single type. The length of an array is established when the.
Arrays, For loop While loop Do while loop
An Introduction to Java – Part I, language basics
Java Language Basics.
Introduction To Programming Information Technology , 1’st Semester
Object Oriented Programming in java
CS2011 Introduction to Programming I Arrays (I)
Arrays Chapter 7.
Arrays in Java.
How do you do the following?
Presentation transcript:

Arrays An array is a structure that holds multiple values of the same type. The length of an array is established when the array is created (at runtime). After creation, an array is a fixed-length structure. An array element is one of the values within an array and is accessed by its position within the array.

Declaring an Array Variable Like declarations for variables of other types, an array declaration has two components: –the array's type, and –the array's name. An array's type is written type[ ], where type is the data type of the elements contained within the array, and [ ] indicates that this is an array. All of the elements within an array are of the same type. Example: int[ ] anArrayOfInteger; float[ ] anArrayOfFloats; boolean[ ] anArrayOfBooleans; Object[ ] anArrayOfObjects; String[ ] anArrayOfStrings; The declaration for an array variable does not allocate any memory to contain the array elements.

Creating an Array In general, the new operator is used to create an array, plus the data type of the array elements, plus the number of elements desired enclosed within square brackets ('[' and ']'). arrayVariable = new elementType[arraySize] Example: int[ ] anArray; … anArray = new int[10]; If the new statement were omitted from the program, the compiler would print an error like the following one and compilation would fail. FileName.java:lineNumber: Variable varName may not have been initialized.

Accessing an Array Element Example: for (int i = 0; i < anArray.length; i++) { anArray[i] = i; System.out.print(anArray[i] + " "); } The value between the square brackets indicates (either with a variable or some other expression) the index of the element to access. In Java, array indices begin at 0 and end at the array length minus 1.

Getting the Size of an Array To get the size of an array, you write arrayname.length Be careful: Programmers new to the Java programming language are tempted to follow length with an empty set of parenthesis. This doesn't work because length is not a method. Length is a property provided by the Java platform for all arrays. The for loop in our sample iterates over each element of anArray, assigning values to its elements. The for loop uses anArray.length to determine when to terminate the loop.

Array Initializers The Java language provides a shortcut syntax for creating and initializing an array. Here's an example of this syntax: boolean[] answers = { true, false, true, true, false }; The length of the array is determined by the number of values provided between { and }. Project Example: ArrayDemo, ArrayDemo2, ArrayDemo3, Histogram

Arrays of Objects Arrays can hold reference types as well as primitive types. That type of array can be created in much the same way to create an array with primitive types. Project Example: ArrayOfString This program creates and populates the array in a single statement. However, an array can be created without putting any elements in it. Example: –String[ ] anArray = new String[5];

Arrays of Objects After the line of code is executed, the array called anArray exists and has enough room to hold 5 string objects. However, the array doesn't contain any strings yet. It is empty. The program must explicitly create strings and put them in the array. Many beginners assume that the previous line of code creates the array and creates 5 empty strings in it. Thus they end up writing code like the following, which generates a NullPointerException: String[ ] anArray = new String[5]; for (int i = 0; i < anArray.length; i++) { // ERROR: the following line gives a runtime error System.out.println(anArray[i].toLowerCase()); }

Arrays of Objects Example: StringArray.java, Project WhatHappen & ThisHappen public class StringArray { public static void main(String[] args) { String[] myString = new String[10]; for (int i = 0; i < myString.length; i ++) { myString[i] = new String(); myString[i] = "String " + i; System.out.println(myString[i]); }

Arrays of Arrays Arrays can contain arrays. Example: String[ ][ ] cartoons = { { "Flintstones", "Fred", "Wilma", "Pebbles", "Dino" }, { "Rubbles", "Barney", "Betty", "Bam Bam" }, { "Jetsons", "George", "Jane", "Elroy", "Judy", "Rosie", "Astro" }, { "Scooby Doo Gang", "Scooby Doo", "Shaggy", "Velma", "Fred", "Daphne" } }; Notice that the sub-arrays are all of different lengths. As with arrays of objects, the sub-arrays must be created explicitly within an array. So if the initializer is not used, we need to write code like the following page:

Arrays of Arrays Example: int[ ][ ] anArray = new int[4][ ]; for (int i = 0; i < anArray.length; i++) anArray[i] = new int[5]; The length of the primary array must be specified when the array is created. The length of the sub-arrays can be leaved unspecified until it’s created. Project Examples: ArrayOfArrays ArrayOfArraysInt

Copying Arrays Use System's arraycopy( ) method to efficiently copy data from one array into another. The arraycopy( ) method requires five arguments: public static void arraycopy( Object source, int srcIndex, Object dest, int destIndex, int length ); The two Object arguments indicate the array to copy from and the array to copy to. The three integer arguments indicate the starting location in each the source and the destination array, and the number of elements to copy.

Copying Arrays This diagram illustrates how the copy takes place: Example: ArrayCopyInt; ArrayCopyString

Copying Arrays The arraycopy method call in the example program begins the copy at element number 2 in the source array. The arraycopy method call puts the copied elements into the destination array beginning at the first element (element 0) in the destination array. The arraycopy copies 7 elements: 'c', 'a', 'f', 'f', 'e', 'i', 'n'. Effectively, the arraycopy method takes the "caffein" out of "decaffeinated", like this: The destination array must be allocated before the arraycopy is called and must be large enough to contain the data being copied.