Unformatted text preview:

Arrays in JAVADeclaring an Array VariableDefining an ArrayGraphical RepresentationWhat happens if …Slide 6Slide 7Array Size through InputDefault InitializationAccessing Array ElementsValidating IndexesSlide 12Reusing Array VariablesInitializing ArraysSlide 15DemonstrationOutputArray LengthChange in Array LengthSample ProgramArrays of ArraysSlide 22Initializing Array of ArraysArrays of Arrays of Varying LengthInitializing Varying Size ArraysArray of Arrays LengthSlide 27Slide 28Triangular Array of ArraysMultidimensional ArraysVarying length in Multidimensional ArraysArrays in JAVACS 340 Software DesignMuhammad TalhaDeclaring an Array Variable•Do not have to create an array while declaring array variable–<type> [] variable_name;–int [] prime;–int prime[];•Both syntaxes are equivalent •No memory allocation at this pointDefining an Array•Define an array as follows:–variable_name=new <type>[N];–primes=new int[10];•Declaring and defining in the same statement:–int[] primes=new int[10];•In JAVA, int is of 4 bytes, total space=4*10=40 bytesGraphical Representation0 1 2 3 4 5 6 7 8 92 1 11 -9 2 1 11 90 101 2primeIndexvalueWhat happens if …•We define –int[] prime=new long[20];MorePrimes.java:5: incompatible typesfound: long[]required: int[]int[] primes = new long[20]; ^•The right hand side defines an array, and thus the array variable should refer to the same type of arrayWhat happens if …•We define–int prime[100];MorePrimes.java:5: ']' expectedlong primes[20]; ^•The C++ style is not permitted in JAVA syntaxWhat happens if …•Valid code:int k=7;long[] primes = new long[k]; •Invalid Code:int k;long[] primes =new long[k];Compilation Output:MorePrimes.java:6: variable k might not have been initializedlong[] primes = new long[k]; ^Array Size through Input….BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));String inData;int num; System.out.println("Enter a Size for Array:");inData = stdin.readLine();num = Integer.parseInt( inData ); // convert inData to intlong[] primes = new long[num]; System.out.println(“Array Length=”+primes.length);….SAMPLE RUN:Enter a Size for Array:4Array Length=4Default Initialization•When array is created, array elements are initialized –Numeric values (int, double, etc.) to 0–Boolean values to false–Char values to ‘\u0000’ (unicode for blank character)–Class types to nullAccessing Array Elements•Index of an array is defined as–Positive int, byte or short values–Expression that results into these types•Any other types used for index will give error –long, double, etc.–Incase Expression results in long, then type cast to int•Indexing starts from 0 and ends at N-1primes[2]=0;int k = primes[2];…Validating Indexes•JAVA checks whether the index values are valid at runtime–If index is negative or greater than the size of the array then an IndexOutOfBoundException will be thrown–Program will normally be terminated unless handled in the try {} catch {}What happens if …long[] primes = new long[20]; primes[25]=33;….Runtime Error:Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 25at MorePrimes.main(MorePrimes.java:6)Reusing Array Variables•Array variable is separate from array itself–Like a variable can refer to different values at different points in the program–Use array variables to access different arraysint[] primes=new int[10];……primes=new int[50];•Previous array will be discarded•Cannot alter the type of arrayInitializing Arrays•Initialize and specify size of array while declaring an array variableint[] primes={2,3,5,7,11,13,17}; //7 elements•You can initialize array with an existing arrayint[] even={2,4,6,8,10};int[] value=even;–One array but two array variables!–Both array variables refer to the same array–Array can be accessed through either variable nameGraphical Representation0 1 2 3 42 4 6 8 10evenvalueDemonstrationlong[] primes = new long[20]; primes[0] = 2; primes[1] = 3; long[] primes2=primes;System.out.println(primes2[0]);primes2[0]=5;System.out.println(primes[0]);Output25Array Length•Refer to array length using length–A data member of array object–array_variable_name.length–for(int k=0; k<primes.length;k++)….•Sample Code:long[] primes = new long[20]; System.out.println(primes.length);•Output: 20Change in Array Length•If number of elements in the array are changed, JAVA will automatically change the length attribute!Sample Programclass MinAlgorithm { public static void main ( String[] args ) { int[] array = { -20, 19, 1, 5, -1, 27, 19, 5 } ; int min=array[0]; // initialize the current minimum for ( int index=0; index < array.length; index++ ) if ( array[ index ] < min ) min = array[ index ] ; System.out.println("The minimum of this array is: " + min ); } } *Program taken from: http://chortle.ccsu.edu/CS151/Notes/chap47/ch47_10.htmlArrays of Arrays•Two-Dimensional arrays–float[][] temperature=new float[10][365];–10 arrays each having 365 elements–First index: specifies array (row)–Second Index: specifies element in that array (column)–In JAVA float is 4 bytes, total Size=4*10*365=14,600 bytesGraphical Representation0 1 2 3 4 5 6 7 8 90 1 2 3 4 5 6 7 8 90 1 2 3 4 5 6 7 8 9Sample[0]Sample[1]Sample[2]Initializing Array of Arraysint[][] array2D = { {99, 42, 74, 83, 100}, {90, 91, 72, 88, 95}, {88, 61, 74, 89, 96}, {61, 89, 82, 98, 93}, {93, 73, 75, 78, 99}, {50, 65, 92, 87, 94}, {43, 98, 78, 56, 99} }; //5 arrays with 5 elements eachArrays of Arrays of Varying Length•All arrays do not have to be of the same lengthfloat[][] samples;samples=new float[6][];//defines # of arrayssamples[2]=new float[6]; samples[5]=new float[101];•Not required to define all arraysInitializing Varying Size Arraysint[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } }; //Three arrays//First array has 3 elements//Second array has 2 elements//Third array has 5 elementsArray of Arrays Lengthlong[][] primes = new long[20][]; primes[2] = new long[30];System.out.println(primes.length); //Number of arraysSystem.out.println(primes[2].length);//Number of elements in the second arrayOUTPUT:2030Sample Programclass unevenExample3 { public static void main( String[] arg ) { // declare and construct a 2D array int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } }; // print out the array for ( int


View Full Document

UIC CS 340 - Software Design

Documents in this Course
Load more
Download Software Design
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Software Design and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Software Design 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?