Arrays in Java. Working with Arrays



Similar documents
In this Chapter you ll learn:

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

AP Computer Science Java Mr. Clausen Program 9A, 9B

arrays C Programming Language - Arrays

Introduction to Java

Two-Dimensional Arrays Summer 2010 Margaret Reid-Miller

Part I. Multiple Choice Questions (2 points each):

Answers to Review Questions Chapter 7

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Introduction to Programming

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

8.1. Example: Visualizing Data

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

AP Computer Science Java Subset

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

5 Arrays and Pointers

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

6.1. Example: A Tip Calculator 6-1

1.4 Arrays Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright /6/11 12:33 PM!

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

Install Java Development Kit (JDK) 1.8

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Some Scanner Class Methods

VB.NET Programming Fundamentals

(Eng. Hayam Reda Seireg) Sheet Java

Object-Oriented Programming in Java

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

JAVA ARRAY EXAMPLE PDF

Using Two-Dimensional Arrays

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

13 File Output and Input

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Topic 11 Scanner object, conditional execution

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

CMSC 202H. ArrayList, Multidimensional Arrays

Using Files as Input/Output in Java 5.0 Applications

Sample CSE8A midterm Multiple Choice (circle one)

Two-Dimensional Arrays. Multi-dimensional Arrays. Two-Dimensional Array Indexing

J a v a Quiz (Unit 3, Test 0 Practice)

Chapter 2 Introduction to Java programming

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Building Java Programs

Building Java Programs

Passing 1D arrays to functions.

Programmierpraktikum

Introduction to Data Structures

IRA EXAMPLES. This topic has two examples showing the calculation of the future value an IRA (Individual Retirement Account).

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Building Java Programs

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

Lecture 5: Java Fundamentals III

Homework/Program #5 Solutions

Programming Languages CIS 443

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Java Basics: Data Types, Variables, and Loops

Pseudo code Tutorial and Exercises Teacher s Version

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

Moving from CS 61A Scheme to CS 61B Java

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Programming and Data Structures with Java and JUnit. Rick Mercer

CS170 Lab 11 Abstract Data Types & Objects

Chapter 2: Elements of Java

Basic Programming and PC Skills: Basic Programming and PC Skills:

Common Data Structures

Comp 248 Introduction to Programming

Chapter 3. Input and output. 3.1 The System class

Building Java Programs

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Project 2: Bejeweled

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

Basics of Java Programming Input and the Scanner class

Example of a Java program

Program Logic to Java GEEN163

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

The resulting tile cannot merge with another tile again in the same move. When a 2048 tile is created, the player wins.

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Array Abstract Data Type

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Introduction to Java. CS 3: Computer Programming in Java

Contents. 9-1 Copyright (c) N. Afshartous

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Moving from C++ to VBA

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Arrays in Java. data in bulk

Event-Driven Programming

PostgreSQL Functions By Example

Chapter 2 Elementary Programming

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Transcription:

Arrays in Java So far we have talked about variables as a storage location for a single value of a particular data type. We can also define a variable in such a way that it can store multiple values. Such a variable is called a data structure. An array is a common data structure used to store a collection of values of the same type, where the collection s size does not change once it is declared. An array is a list of data items represented by a single variable name. It can be thought of as a collection of variables all of which are referenced using that single name. Each value in the array is called an element and individual elements are accessed using an index which is an integer enclosed in [ ]. The index specifies the position of a particular element in the array. Declaring arrays In defining an array in Java we have to indicate that it is an array and also specify the data type of the elements that will be stored there. For example if we wanted to define an array called grades that contained 5 elements of type double, we could write the following: final int NUM_GRADES = 5; double [] grades = new double [NUM_GRADES]; The word double indicates the data type of the elements in the array, the [] indicates that it will be an array, and grades is the name of the array. The expression to the right of the = operator instructs the compiler to allocate an array capable of storing 5 (the value of the constant NUM_GRADES) double values. NOTE: An array is a reference data type. The memory location of the array is an address to the starting location of the array itself. Array Initialization An array s items are automatically initialized to the default value of their type. For the numeric types the default values are 0.0 for floats and 0 for integers. For reference types the default value is null. Note that normal variables are not automatically initialized. This default initialization is for arrays only. Arrays can also be initialized using a special { notation. This notation can only be used at the time an array is being declared. It cannot be used for regular assignment statements. In the following example, a new int[] will be created and its size will be 7 (i.e., the number of values specified in brackets). int[] scores = {0, 1, 2, 3, 4, 5, 6 ; Accessing Array Elements An individual element of an array can be accessed by specifying the name of the array, followed by the element s position in the array (it s index) which is enclosed in brackets. Like characters 1

in a string, the first element of the array has an index of 0. An array element can be thought of as a variable whose type is the array s item-type. The array subscript operation validates each access to an array. If the subscript is outside the range of valid index values things can go wrong!!!! The array length property contains the number of elements in an array. It is found by giving the name of the array followed by a dot and the word length (e.g., grades.length). Note that length is a property, not a method so there are no ( ) after the word length as there is for a String object s length() method. Since the index of an array begins with 0, the index of the last element is always the array s length - 1. Thus the expression anarray[anarray.length - 1] can be used to access the last element of the array. Calling Methods with Arrays Arrays can be passed as parameters but again there has to be an indication that the parameter is an array. If we were to pass grades as a parameter, the receiving method needs to define a parameter capable of storing the array s handle. NOTE: When an array is passed as a parameter it really only passes the address of the starting location of the array (the handle). This is done by placing a pair of brackets between a parameter s type and its name. For example, if we had a method with an array parameter called anarray we could define it as follows: public static double average(double[] anarray) Processing Array Elements A for loop is ideal for accessing each of the elements of an array. For example, to get grade information into an array, we could write the following: System.out.print("Enter grade #" + (i+1)+ " of " + array.length + ": "); array[i] = keyboard.nextdouble(); A complete program for entering grades, determining their average, and printing them and the average is as follows: /* This program will read in grades, find the average and print out * the average of those grades * @author Carter * */ import java.util.scanner; 2

public class Grades { public static void main(string[] args) { final int NUM_GRADES = 5; double[] grades = new double[num_grades]; readgradesinto(grades); // this is a call to a method that // passes an array parameter System.out.printf( "\nthe average is %.2f%n", average(grades)); print(grades); private static void readgradesinto(double[] array) { Scanner keyboard = new Scanner (System.in); System.out.println("To compute the grade "); System.out.print("Enter grade #" + (i+1)+ " of " + array.length + ": "); array[i] = keyboard.nextdouble(); // end of for loop public static double average(double[] array) { double sum = 0.0; sum = sum + array[i]; // end of for loop return (sum / array.length); public static void print(double[] array){ System.out.println("Grade #" + (i+1) + ": " + array[i]); The for each loop Java has a special version of the for loop called a for-each loop. In finding the average of grades we could write an average() method that calculates the sum of all grades as follows: double sum =0.0; for (double item : anarray) { sum = sum + item; return sum / anarray.length; This repeats the statement sum = sum + item; for each item in the array. NOTE: the for each loop can be used to read an array s items, but cannot be used to write into them. For example we could not use a for each loop for readgradesinto() above because that reads a number from the keyboard and writes it to an array element. However, we could use it for average() and print() since in those methods we are only reading an array s items. 3

Arrays and Memory An array s elements reside in adjacent memory locations and Java s subscript operator makes use of this adjacency to access any element of an array in the same amount of time. For example, when Java evaluates the expression anarray[i], it multiplies the index i by the size of one item (the amount of storage space that the data type uses) and adds the resulting product to the reference location specified in anarray. [0] [1] [2] [3] [4] [5] [6] The name of the array is actually a reference (handle) that points to the starting address of the array. anarray[4] multiplies 4 * size of one element resulting in the address of the fifth element of the array. An array is a random access data structure which means it takes the same amount of time to access any item in the. Arrays are not good, however, if we want to change the contents of the array by inserting an element in between existing elements. It is not uncommon for some positions in an array to be unused. For example, if we were reading an undetermined number of grades (with a maximum of 30) we would make our array size 30, but keep track of how many elements are actually used (i.e., read in). We could then pass that number as an additional parameter to any method that uses the array. The size of our array for practical purposes is not the actual size as determined by the length property, but rather the number of elements in the array that are actually used. The grades program would now be as follows. import java.util.scanner; public class GradesUndeterminedAmount { public static void main(string[] args) { final int NUM_GRADES = 30; double [] grades = new double[num_grades]; int sizeofarray; // The actual amount of grades read in sizeofarray = readgradesinto(grades); System.out.printf( "\nthe average is %.2f%n", average(grades, sizeofarray)); print(grades, sizeofarray); public static int readgradesinto(double[] array) { Scanner keyboard = new Scanner (System.in); int arraysize = 0; double grade; System.out.print("Enter grade #" + (arraysize + 1) + " enter 1 to quit ); grade=keyboard.nextdouble(); while (grade >= 0) { array[arraysize] = grade; arraysize++; // increase size by 1 4

System.out.print("Enter grade #" + (arraysize+1)+ " enter -1 to quit"); grade=keyboard.nextdouble(); return arraysize; public static double average(double [] anarray, int arraysize) { double sum = 0.0; for (int i = 0; i < arraysize; i++) { sum = sum + anarray[i]; return sum / arraysize; public static void print(double[] arr, int arraysize){ for (int i = 0; i < arraysize; i++) { System.out.println("Grade #" + (i+1) + ": " + arr[i]); Multidimensional Arrays Thus far we have only considered arrays that have a single dimension: length. That length determined the amount of space needed by the array. They are referred to as 1-dimensional arrays. We can also declare multiple dimensional arrays. For example, a 2-dimensional array could be used to store data in a table. A 2-dimensional array can be declared as follows: double [][] mytable = null; We use two pairs of brackets instead of one to indicate that this is a two-dimensional array. In general we would use N brackets for an N-dimensional array. We can allocate memory for a multi-dimensional array though the use of the new operator. mytable = new double[rows][columns]; Where rows represents the number of rows in our table and columns represents the number of columns. We can also initialize the positions in a multidimensional (in this case two) array as follows: double[][] anarray = { {0, 1, 2, 3, 4, 5, 6, {7, 8, 9, 10, 11, 12, 13 {14, 15, 16, 17, 18, 19, 20 ; This creates a two-dimensional array with 3 rows and 7 columns. To access elements in a one-dimensional array we used one subscript operator. To access an element in a 2-dimensional array, we use two subscript operators. return mytable[row][col]; // access element at row, col. 5