arrays in java
DESCRIPTION
Arrays in Java. 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 > - PowerPoint PPT PresentationTRANSCRIPT
![Page 1: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/1.jpg)
Arrays in Java
![Page 2: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/2.jpg)
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: 0Max Index: Size-1
![Page 3: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/3.jpg)
Creating an Array0 <data_type>[] <name_of_array> // declares an array of integers int[ ] anArray;
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).
![Page 4: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/4.jpg)
Example0 byte[] anArrayOfBytes; 0 short[] anArrayOfShorts; 0 long[] anArrayOfLongs; 0 float[] anArrayOfFloats; 0 double[] anArrayOfDoubles; 0 boolean[] anArrayOfBooleans; 0 char[] anArrayOfChars; 0 String[] anArrayOfStrings;
// this form is discouraged float anArrayOfFloats[ ];
![Page 5: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/5.jpg)
Initializing an Array0 One way to create an array is with the new operator.
int[] anArray= new int[5];
0 0 0 0 0anArray
0 1 2 3 4
Variable anArray may not have been initialized
If missing
![Page 6: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/6.jpg)
Accessing an Array
12 11 2 3 25anArray
0 1 2 3 4
anArray[0] anArray[2] anArray[4] anArray[1] anArray[3]
int[] anArray= new int[5];anArray[0]=12;anArray[1]=11;anArray[2]=2;anArray[3]=3;anArray[4]=25;
Each array element is accessed by its numerical index:
![Page 7: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/7.jpg)
Shortcut Syntax
0 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 }.
![Page 8: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/8.jpg)
Summary
0 Each element in an array is just a variable0 Anything you would put in a variable of that type can
be assigned to an array element of that type. 0 An array starts at 0.0 An array ends at size -1. (accessing indexes other than the declared index will result to “ArrayIndexOutOfBounds” error during runtime)
![Page 9: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/9.jpg)
Example: Reference Types and Arrayspublic 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! "); } }
![Page 10: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/10.jpg)
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; } }}
![Page 11: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/11.jpg)
Output
![Page 12: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/12.jpg)
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]+" "); x = x + 1; }
![Page 13: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/13.jpg)
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; } }}
![Page 14: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/14.jpg)
2D and multidimensional arrays0 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];
0 Each element, therefore, must be accessed by a corresponding number of index values.
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 1 2 3 4
0
1
2
3
![Page 15: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/15.jpg)
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]); } }
![Page 16: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/16.jpg)
Copying arrays
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)); }
} }
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
![Page 17: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/17.jpg)
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.
![Page 18: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/18.jpg)
CodeMagnets:
Seatwork : ½ lengthwise paperA 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.
![Page 19: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/19.jpg)
Answerclass 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; } }}
![Page 20: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/20.jpg)
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
![Page 21: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/21.jpg)
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
![Page 22: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/22.jpg)
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 for ( int counter = 0; counter < array.length; counter++ ) System.out.println( " " + counter+ " " + array[ counter ] ); } // end main } // end class
![Page 23: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/23.jpg)
Seatwork: 1 whole yellow paper. (by pair)
1. 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
![Page 24: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/24.jpg)
Answer no.1 & 2import 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]); } }
![Page 25: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/25.jpg)
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
![Page 26: Arrays in Java](https://reader036.vdocument.in/reader036/viewer/2022081504/5681383b550346895d9fe549/html5/thumbnails/26.jpg)
2D Array example:Initializing two-dimensional arrayspublic 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