1 / 26

Arrays in Java

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 >

Download Presentation

Arrays in Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Arrays in Java

  2. 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

  3. Creating an Array • <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).

  4. Example • byte[] anArrayOfBytes; • short[] anArrayOfShorts; • long[] anArrayOfLongs; • float[] anArrayOfFloats; • double[] anArrayOfDoubles; • boolean[] anArrayOfBooleans; • char[] anArrayOfChars; • String[] anArrayOfStrings; // this form is discouraged float anArrayOfFloats[ ];

  5. 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 0 1 2 3 4 0 0 0 0 0 anArray

  6. Accessing an Array 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: 0 1 2 3 4 12 11 2 3 25 anArray anArray[0] anArray[2] anArray[4] anArray[1] anArray[3]

  7. 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 }.

  8. 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)

  9. 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! "); } }

  10. 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; } } }

  11. Output

  12. Simple Tracing Sample intx = 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; }

  13. Seatwork : Be the compiler.Correct any error, and predict the output 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; } } } 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; } } }

  14. 2D and multidimensional arrays • You can also declare an array of arrays (also known as a multidimensionalarray) 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 0 1 2 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

  15. 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]); } }

  16. Copying arrays public static void arraycopy(Object src, intsrcPos, Object dest, intdestPos, 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)); } } }

  17. 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.

  18. 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. CodeMagnets:

  19. 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; } } }

  20. 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

  21. 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

  22. 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

  23. 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

  24. Answer no.1 & 2 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]); } } 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]);}} } }

  25. 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

  26. 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

More Related