170 likes | 275 Views
This guide covers the fundamental concepts of arrays in Java, including how they are structured as continuous memory spaces and their instantiation. It explains the differences between array types, such as int[], char[], and String[], and delves into advanced topics including multi-dimensional arrays, indexing, and exception handling, like ArrayIndexOutOfBoundsException. Additionally, it provides practical examples of using arrays for storing data such as student scores and grades while demonstrating how to work with array methods and object references.
E N D
Arrays A list of values Conceptually, a continuous memory space
public String() { this.offset = 0; this.count = 0; this.value = new char[0]; }
i e C o c n e c u e p m r S t String Name = new String (“Computer Science”); name “Computer Science” name 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 “Computer Science”.subString(4,8) returns “uter “ name.subString(4,8) returns “uter”
1000 numbers • smallest
int[] height = new int[11] • int[] does not includes the size • Instantiation height using new Bound checking – automatic height[index] If index = 10 If index = 12 ArrayIndexOUtOfBoundsException
int[] height; • int height[]; • int[] scores = {87,98,68,87,65,100} • Char[] vowels = {‘A’, ‘E’, ‘I’, ’O’, ’U’}
Array as parameters • Array is an object (call by reference) • copy the reference • call by value if array element
Arrays of objects • String[] words = new String[5]; words
For (int index = 0; index < LIMIT; index++) • system.out.println(list[index]); For (int value : list) System.out.println(value);
Grade Grade Range
int[] anArray ; • byte[] anArrayOfBytes; • short[] anArrayOfShorts; • long[] anArrayOfLongs; • float[] • char[] anArrayOfChars; • String[] anArrayOfStrings;
Using final tag. for(index = 0; index < final; index ++) section= scan.nextInt(); Read data until the read data is meaningless For example if the section number is 0, stop section = scan.nextInt(); While (section != 0) { statement(s); section = scan,nextInt(); }
Read up to 50 students5 scores / studentGrade depends on Avg.highest grade and namelowest grade and name • Student Section Private avg Private gNoA Instantiate 6 students object letterGrade lowerBound numbers names chagenumber getnumber Getname changename
Multi dimension • Array whose components are themselves array • Array element is an array MArray
Multi dimensional array –java does not directly support • Use array of array reference • Ragged array
arraycopy • char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' }; • char[] copyTo = new char[7]; • for (i=2; i<=7; i++) • copyTo[i] = copyFrom[i];