Arrays in Java Prepare 1 whole yellow paper.

Slides:



Advertisements
Similar presentations
Arrays.
Advertisements

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).
Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
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.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Java Unit 9: Arrays Declaring and Processing Arrays.
 Pearson Education, Inc. All rights reserved Arrays.
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.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
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.
Lecturer : Sakuni Sellapperuma. Introduction An array is a container object that holds a fixed number of values of a single type. The length of an array.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Computer Programming 12 Mr. Jean April 24, The plan: Video clip of the day Upcoming Quiz Sample arrays Using arrays More about arrays.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
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.
Arrays.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
Array and String.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
Chapter 9 Introduction to Arrays Fundamentals of Java.
Java Programming Language Lecture27- An Introduction.
Lecture 7: Arrays Michael Hsu CSULA 3 Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Functions + Overloading + Scope
Exercise 1- I/O Write a Java program to input a value for mile and convert it to kilogram. 1 mile = 1.6 kg. import java.util.Scanner; public class MileToKg.
Arrays in JAVA Visit for more Learning Resources.
Elementary Programming
Computer Programming BCT 1113
Array, Strings and Vectors
Chapter 5: Control Structures II
Repetition-Counter control Loop
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.
Java Programming: From Problem Analysis to Program Design, 4e
SELECTION STATEMENTS (1)
INPUT STATEMENTS GC 201.
Data Structures Array - Code.
Java How to Program, Late Objects Version, 10/e
Chapter 6 Arrays Solution Opening Problem
Nested Loop Review and Two-Dimensional Arrays
An Introduction to Java – Part I, language basics
Chapter 8 Multi-Dimensional Arrays
Chapter 2: Basic Elements of Java
Building Java Programs
Java Language Basics.
Arrays Kingdom of Saudi Arabia
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Chapter 7 Multidimensional Arrays
EKT150 : Computer Programming
Introduction To Programming Information Technology , 1’st Semester
Defining methods and more arrays
Cs212: Data Structures Computer Science Department Lecture 2: Arrays.
Data Structures Array - Code.
MSIS 655 Advanced Business Applications Programming
Fall 2018 CISC124 2/15/2019 CISC124 TA names and s will be added to the course web site by the end of the week. Labs start next week in JEFF 155:
Arrays.
Announcements Lab 6 was due today Lab 7 assigned this Friday
Chapter 6 Arrays.
Single-Dimensional Arrays chapter6
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
Arrays in Java.
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Chapter 7 Multidimensional Arrays
Java SE 7 One and Multi Dimensional Arrays Module 6
Chapter 8 Multidimensional Arrays
How do you do the following?
Presentation transcript:

Arrays in Java Prepare 1 whole yellow paper

ARRAYS -is a container object that holds a fixed number of values of a single type -Each item in an array is called an element -each element is accessed by its numerical index Min Index: 0 Max Index: Size-1

Creating an Array <data_type>[] <name_of_array> // declares an array of integers int[ ] anArray; Like declarations for variables of other types, an array declaration has two components: the array's type and the array's name. The square brackets -are special symbols indicating that this variable holds an array. The size of the array is not part of its type (which is why the brackets are empty).

Example byte[] anArrayOfBytes; short[] anArrayOfShorts; long[] anArrayOfLongs; float[] anArrayOfFloats; double[] anArrayOfDoubles; boolean[] anArrayOfBooleans; char[] anArrayOfChars; String[] anArrayOfStrings; Declaring arrays of other types. You can also place the square brackets after the array's name. However, convention discourages this form; the brackets identify the array type and should appear with the type designation. // this form is discouraged float anArrayOfFloats[ ];

Initializing an Array One way to create an array is with the new operator. int[] anArray= new int[5]; If missing Variable anArray may not have been initialized anArray 0 1 2 3 4 If this statement were missing, the compiler would print an error like the following, and compilation would fail.

Accessing an Array int[] anArray= new int[5]; anArray[0]=12; Each array element is accessed by its numerical index: System.out.println("Element 1 at index 0: " + anArray[0]); System.out.println("Element 2 at index 1: " + anArray[1]); System.out.println("Element 3 at index 2: " + anArray[2]); System.out.println("Element 4 at index 3: " + anArray[3]); System.out.println("Element 5 at index 4: " + anArray[4]); 12 11 2 3 25 anArray 0 1 2 3 4 anArray[0] anArray[2] anArray[4] anArray[1] anArray[3]

Shortcut Syntax To create and initialize an array int[] anArray= {12,11,2,3,25} Here the length of the array is determined by the number of values provided between { and }.

Summary Each element in an array is just a variable Anything you would put in a variable of that type can be assigned to an array element of that type. An array starts at 0. An array ends at size -1. (accessing indexes other than the declared index will result to “ArrayIndexOutOfBounds” error during runtime) In other words, it can be one of the 8 primitive data types or a reference variable

Example: Reference Types and Arrays public class Dog{ private String name; public void setName(String newName){ name=newName; } public String getName(){ return name; public void bark(){ System.out.println(name+ " says Ruff! "); Create 3 dog objects and access them

public class B { public static void main(String [] args){ Dog dog1 = new Dog(); // make a Dog object and access it dog1.setName("Bart"); dog1.bark(); Dog[] myDogs = new Dog[3]; //now make a Dog array myDogs[0]=new Dog(); myDogs[1]=new Dog(); myDogs[2]=dog1; myDogs[0].setName("Fred"); //accessing the dogs using the array myDogs[1].setName("Marge"); //what is myDogs[2] name? System.out.println("last dog's name is: "+myDogs[2].getName()); int x=0; //call all your dogs and make them bark while(x<3){ //since there are 3 dogs myDogs[x].bark(); x=x+1; }

Output

Simple Tracing Sample int x = 0; int[] hq = new int[5]; while ( x < 3 ){ hq[x] = x; x = x + 1; } hq[3] = hq[1]; hq[4] =hq[1] ; hq[3] = 0; hq [4]= hq [0] ; hq[0] = hq[3]; hq[3] =hq[2]; hq[2] = hq [0] ; x=0; while ( x < 5 ){ System.out.print(hq[x]+" ");

Seatwork : Be the compiler.Correct any error, and predict the output 1. ) class Hobbit{ String name; public static void main(String[] a){ Hobbit[] h = new Hobbit[3]; int z=0; while(z<=4){ h[z]=new Hobbit(); h[z].name="bilbo"; if(z==1){ h[z].name="frodo";} if(z==2){ h[z].name="sam";} System.out.println(h[z].name + " is a "); z = z + 1; } 2.) public class Books{ String title; String author; } public class BooksTestDrive{ public static void main(String[] a){ Books[] myBooks = new Books[3]; myBooks[0]= new Books(); myBooks[1]= new Books(); myBooks[2]= new Books(); int x = 0; myBooks[0].title="The Java Cookbook"; myBooks[1].title="Programming Java"; myBooks[2].title="Java Language"; myBooks[0].author="Maria"; myBooks[1].author="Pedro"; myBooks[2].author="Juan"; while(x<3){ System.out.print(myBooks[x].title); System.out.print(" by “+" "); System.out.println(myBooks[x].author); x=x+1; }

2D and multidimensional arrays You can also declare an array of arrays (also known as a multidimensional array) by using two or more sets of square brackets, such as int[][] nums=new int[4][5]; Each element, therefore, must be accessed by a corresponding number of index values. 0 1 2 3 4 1 2 3

Example class MultiDimArrayDemo { public static void main(String[] args) { String[][] names = { {"Mr. ", "Mrs. ", "Ms. "}, {"Smith", "Jones"} }; System.out.println(names[0][0] + names[1][0]); System.out.println(names[0][1] + names[1][1]); System.out.println(names[0][1] + names[2][0]); }

Copying arrays class ArrayCopyDemo { public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) class ArrayCopyDemo { public static void main(String[] args) { char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' }; char[] copyTo = new char[7]; System.arraycopy(copyFrom, 2, copyTo, 0, 7); for(int x=0;x<7;x++){ System.out.print(x+” “); System.out.println(new String(copyTo)); } System.out.println(new String(copyTo));

Another Example: Copying Arrays int [] myArray = { 1,2,3,4,5,6 }; int [] hold = { 10,9,8,7,6,5,4,3,2,1} //copy all of the myArray array to the hold array, //starting with the 0th index System.arraycopy(myArray, 0, hold, 0, myArray.length); Note: the System.arraycopy method copies references, not objects, when dealing with arrays of objects. The objects themselves do not change.

Code Magnets: Seatwork : ½ lengthwise paper A working java program is all scrambled up. Reconstruct the code snippets to make a working java program that produces the output below. Some of the curly braces fell on the floor and they are small to Pick up, so feel free to add as many of those as you need. class B{ public static void main(String[] args) { int [] index = new int[4]; index[0] =1; index[1]= 3; index[2]= 0; index[3]=2; String [] islands = new String[4]; islands[0] ="Bermuda"; islands[1] = "Fiji"; islands[2]= "Azores"; islands[3] ="Cozumel"; int y = 0; int ref; while (y < 4) { ref = index[y]; System.out.print("island ="); System.out.println(islands[ref]); y = y + 1; }

Answer class SeatworkArray{ public static void main(String[] args) { int [] index = new int[4]; index[0] =1; index[1]= 3; index[2]= 0; index[3]=2; String [] islands = new String[4]; islands[0] ="Bermuda"; islands[1] = "Fiji"; islands[2]= "Azores"; islands[3] ="Cozumel"; int y = 0; int ref; while (y < 4) { ref = index[y]; System.out.print("island ="); System.out.println(islands[ref]); y = y + 1; }

Array example: Initializing the elements of an array to default values of zero. public class InitArray{ public static void main( String[] args ){ int[] array; // declare array named array array = new int[ 10 ]; // create the array object System.out.println( "Index" + " " + "Value" ); // column headings for ( int counter = 0; counter < array.length; counter++ ) System.out.println( " "+ counter + " " + array[counter] ); } // end main } // end class InitArray

Array example: Initializing the elements of an array with an array initializer public class InitArray2 { public static void main( String[] args ) { // initializer list specifies the value for each element int[] array = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; System.out.println( "Index"+" " + "Value" ); // column headings // output each array element's value for ( int counter = 0; counter < array.length; counter++ ) System.out.println( " " + counter + " " + array[ counter ] ); } // end main } // end class

Array example: Calculating the values to be placed into the elements of an array public class InitArray3 { public static void main( String[] args ) { final int ARRAY_LENGTH = 10; // declare constant int[] array = new int[ ARRAY_LENGTH ]; // create array // calculate value for each array element for ( int counter = 0; counter < array.length; counter++ ) array[ counter ] = 2 + 2 * counter; System.out.println( "Index"+ " " + "Value" ); // column headings // output each array element's value System.out.println( " " + counter+ " " + array[ counter ] ); } // end main } // end class

Seatwork: 1 whole yellow paper. (by pair) Create a program that ask to enter 10 integers as elements of an array and display in column 1 all even integers and in column 2 all odd integers with column headings even and odd. 2. Create a program that accept a five characters as elements of an array and display the reverse. Example: characters: hallo display: ollah

Answer no.1 & 2 import java.util.Scanner; public class RevChar { import java.util.Scanner; class OddEven { public static void main(String[] args) { Scanner input = new Scanner(System.in); final int a =10; int[] num = new int[a]; for (int x=0; x<num.length; x++){ System.out.println("enter an integer: "); num[x]=input.nextInt();} System.out.println("ODD"+" "+"EVEN"); for (int y=0; y<num.length; y++){ if((num[y]%2) == 0){ System.out.println(" "+num[y]);} else {System.out.println(num[y]);}} } import java.util.Scanner; public class RevChar { public static void main(String[] args) { String var; char[] a = new char[5]; Scanner x= new Scanner(System.in); System.out.println("Enter a string"); var=x.next(); a[0]=var.charAt(0); a[1]=var.charAt(1); a[2]=var.charAt(2); a[3]=var.charAt(3); a[4]=var.charAt(4); for (int y=a.length-1;y>=0; y--) System.out.print(a[y]); }

Array example: Computing the sum of the elements of an array public class SumArray{ public static void main( String[] args ){ int[] array = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 }; int total = 0; // add each element's value to total for ( int counter = 0; counter < array.length; counter++ ) total += array[ counter ]; System.out.println( "Total of array elements: “ + total ); } // end main } // end class SumArray

2D Array example:Initializing two-dimensional arrays public class TwoDArray { // create and output two-dimensional arrays public static void main( String[] args ) { int[][] array1 = { { 1, 2, 3 }, { 4, 5, 6 } }; int[][] array2 = { { 1, 2 }, { 3 }, { 4, 5, 6 } }; System.out.println( "Values in array1 by row are" ); outputArray( array1 ); // displays array1 by row System.out.println( "\nValues in array2 by row are" ); outputArray( array2 ); // displays array2 by row } // end main // output rows and columns of a two-dimensional array public static void outputArray(int[][] array ) { // loop through array's rows for ( int row = 0; row < array.length; row++ ){ // loop through columns of current row for ( int column = 0; column < array[ row ].length; column++ ) System.out.print( array[ row ][ column ] ); System.out.println(); // start new line of output } // end outer for } // end method outputArray } // end class