1 / 35

Intro to Arrays in Java

Learn about arrays in Java, how to declare and access array elements, and common array operations.

aborg
Download Presentation

Intro to 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 • An array is a group of contiguous locations that all have the same name and the same type. x x[0] x[1] x[2] x[3] x[4] x[5] • Accessing array elements: arrayname[index] where index is an integer expression x[0]=2; i=2; x[i+1]=x[i]; CS101 - Algorithms & Programming I

  2. Arrays (cont.) • The values held in an array are called array elements • An array stores multiple values of the same type – the element type • The element type can be a primitive type or an object reference • Therefore, we can create an array of integers, an array of characters, an array of String objects, etc. • In Java, the array itself is an object that must be instantiated CS101 - Algorithms & Programming I

  3. 79 scores 87 94 82 67 98 87 81 74 91 Arrays (cont) • Another way to depict an array: CS101 - Algorithms & Programming I

  4. Declaring and Allocating Arrays type[] arrayname = new type[arraysize]; int[] x; x = new int[8]; int[] y = new int[10]; type[] arrayname = { values }; int[] y = {1,3,5,8};allocates an integer array with size 4 (index range:0-3) with initial values. Other Notation: typearrayname[]; int x[]; We prefer the first notation because it is consistent with other declarations. Array Length: arrayname.length x.length  8 CS101 - Algorithms & Programming I

  5. Bounds Checking • Once an array is created, it has a fixed size • An index used in an array reference must specify a valid element • the index value for an array with size n must be in range 0 to n-1 • if the array codes can hold 100 values, it can be indexed using only the numbers 0 to 99 • The Java interpreter throws an ArrayIndexOutOfBoundsException if an array index is out of bounds ( bounds checking) • It’s common to introduce off-by-one errors when using arrays • Each array object has a public constant called length that stores the size of the array • It is referenced using the array name:scores.length • Note that length holds the number of elements, not the largest index for (int index=0; index <= 100; index++) codes[index] = index*50 + epsilon; CS101 - Algorithms & Programming I

  6. Array -- Examples Reading values of an int array: int[] x = new int[100]; for (i=0; i<x.length; i++) System.out.println(“Enter an integer: “); x[i] = scan.nextInt(); } Shifting values of an int array: int temp = x[0]; for (i=0; i<x.length-1; i++) x[i]=x[i+1]; x[x.length-1]=temp; CS101 - Algorithms & Programming I

  7. Array – Examples (cont.) Finding the location of the maximum value in an int array: int loc = 0; for (i=1; i<x.length; i++) if(x[i]>x[loc]) loc=i; Finding the first location of a given value in an int array: int loc, i=0; while ((i<x.length) && (x[i]!=item)) i=i+1; if (i>=x.length) loc=-1; // not found else loc=i; // found CS101 - Algorithms & Programming I

  8. Array – Examples (cont.) Finding summation of the values in an int array: int sum=0; for (i=0; i<x.length; i++) sum=sum+x[i]; Reversing the contents of an int array: int temp,i,j; for (i=0,j=x.length-1; i<j; i++, j--) { temp=x[i]; x[i]=x[j]; x[j]=temp; } CS101 - Algorithms & Programming I

  9. Passing Arrays to Methods • Since arrays are also objects, they are passed into method by call-by-reference. • A pointer to the array is passed into the method. • The contents of the array pointed by an actual parameter can be changed by the method. static void m(int[] x) { int i, temp; temp=x[0]; for (i=0; i<(x.length-1); i++) x[i]=x[i+1]; x[x.length-1]=temp; } // in main int[] a = {3,5,7,8}; m(a); // the content of a will be changed by m CS101 - Algorithms & Programming I

  10. Passing Arrays into Methods -- Example static void findprimes(int[] p, int n) { int i, val; p[0]=2; val=3; i=1; while (i<n) { if (isprime(val,p,i)) { p[i]=val; i++; } val=val+1; } } static boolean isprime(int v, int[] p, int lastprimeloc) { boolean primeflag=true; int i=0; while (primeflag && (i<lastprimeloc)) if (v%p[i] == 0) primeflag=false; else i++; return primeflag; } CS101 - Algorithms & Programming I

  11. Passing Arrays into Methods – Example (cont.) // in main int i; int[] primes = new int[100]; findprimes(primes,10); System.out.println(“First 10 Primes:”); for (i=0; i<10; i++) System.out.println(primes[i]); CS101 - Algorithms & Programming I

  12. Arrays of Objects • The elements of an array can be object references • The following declaration reserves space to store 5 references to String objects String[] words = new String[5]; • It does NOT create the String objects themselves • Initially an array of objects holds null references • Each object stored in an array must be instantiated separately CS101 - Algorithms & Programming I

  13. - words - - - - Arrays of Objects • The words array when initially declared: • At this point, the following reference would throw a NullPointerException: System.out.println (words[0]); CS101 - Algorithms & Programming I

  14. “friendship” words “loyalty” “honor” - - Arrays of Objects • After some String objects are created and stored in the array: words[0] = “friendship”; words[1] = “loyalty”; words[2] = “honor”; CS101 - Algorithms & Programming I

  15. Arrays of Objects • Keep in mind that String objects can be created using literals • The following declaration creates an array object called verbs and fills it with four String objects created using string literals String[] verbs = {"play", "work", "eat", "sleep"}; CS101 - Algorithms & Programming I

  16. Multi-Dimensional Arrays • Allocation of two-dimensional array: int[][] x = new int[5][3]; • Accessing elements of a two-dimensional array: x[0][0] = 5; • Initializing a two-dimensional array: int[][] a = {{3,5,7},{8,6,9}}; CS101 - Algorithms & Programming I

  17. Multi-Dimensional Arrays -- Example // An,m* Bm,k Cn,k public static void matrixmult(int[][] a, int[][] b, int[][] c, int n, int m, int k) { int i,j,p; for (i=0; i<n; i++) for (j=0; j<k; j++) { c[i][j]=0; for (p=0; p<m; p++) c[i][j]=c[i][j] + a[i][p] * b[p][j]; } } CS101 - Algorithms & Programming I

  18. Arrays of -Varying Length • The size of each row of a two-dimensional array can be different; int[][] x; x = new int[5][]; x[0] = new int[1]; x[1] = new int[2]; x[2] = new int[3]; x[3] = new int[4]; x[4] = new int[5]; x.length  5 x[0].length  1 x[1].length  2 ? x[1] = new int[10]; x CS101 - Algorithms & Programming I

  19. Different Types for Arrays String[] names = {“john”,”mark”,”mary”,”cindy”}; boolean[] bvals = new boolean[10]; char[] charray = {‘i’,’l’,’y’,’a’,’s’}; char array is not a string. Reading 100 names from the keyboard: String[] names = new String[100]; for (i=0; i<100; i++) names[i] = scan.nextLine(); CS101 - Algorithms & Programming I

  20. String and char Array • Strings in Java are not char arrays (in C and C++ strings are char arrays). • But, we convert a char array into a string or a string into a char array. char array into string: char[] name = {‘m’,’a’,’r’,’k’}; String aname = new String(name}; string into char array: String aname = “mary”; char[] name = aname.toCharArray(); CS101 - Algorithms & Programming I

  21. Strings • A string is a sequence of characters. • Java provides two classes to support strings: • String class – the instances of String class are constants, ie. the content of a String object cannot be changed after its creation. • StringBuffer class – the instances of StringBuffer class are mutable, ie. the content of a StringBuffer object can be changed after its creation. • The String class has some unique privileges not shared by ordinary classes. • A string can be created using string literals. • Operator + can be applicable to strings. • The characters in a string indexed by 0 to n-1, where n is the length of the string. COP 3330 Object Oriented Programming

  22. String Class • Creation of a String object. String s = new String(“abc”); String s = “abc”; • Add operator: String s1 = “abc”; String s2 = “de”; String s3 = s1 + s2; • String class has a lot of methods. These methods are useful to manipulate strings. CS101 - Algorithms & Programming I

  23. length and charAt int length() – this instance method returns the length of the string. String s=“abc”; s.length()  returns 3 char charAt(int index) – this instance method returns the character at the given index. String s=“abcde”; s.length();  5 s.charAt(0);  ‘a’ s.charAt(1);  ‘b’ s.charAt(4);  ‘e’ s.charAt(5);  error CS101 - Algorithms & Programming I

  24. indexOf int indexOf(char c) int indexOf(char c, int index) Returns the index of the first occurrence of the character c in the current object, no less than index (default 0). Returns –1 if there is no such occurrence. String s=“ababc”; s.indexOf(‘b’)  1 s.indexOf(‘b’,2)  3 int indexOf(String s2) int indexOf(String s2, int index) Returns the index of the first occurrence of the string s2 in the current object, no less than index (default 0). Returns –1 if there is no such occurrence. String s=“daabcabc”; String s2=“ab”; s.indexOf(s2)  2 s.indexOf(s2,3)  5 CS101 - Algorithms & Programming I

  25. substring String substring(int startindex) String substring(int startindex, int lastindex) Returns the substring of the current object starting from startindex and ending with lastindex-1 (or the last index of the string if lastindex is not given) String s=“abcdef”; s.substring(1) “bcdef” s.substring(3) “def” s.substring(1,4)  “bcd” s.substring(3,5)  “de” CS101 - Algorithms & Programming I

  26. equals and equalsIgnoreCase boolean equals(String s2) boolean equalsIgnoreCase(String s2) Returns true if the current object is equal to s2; otherwise false. equalsIgnorecase disregards the case of the characters. String s=“abc”; s.equals(“abc”)  true s.equals(“abcd”)  false s.equals(“aBc”)  false s.equalsIgnoreCase(“aBc”)  true CS101 - Algorithms & Programming I

  27. StringBuffer Class • StringBuffer constructors: StringBuffer() StringBuffer(int size) Returns an instance of the StringBuffer class that is empty but has an initial capacity of size characters (default 16 characters). StringBuffer(String arg) Creates an instance of the StringBuffer class from the string arg. • length and charAt methods are also defined for StringBuffer class. CS101 - Algorithms & Programming I

  28. append and insert StringBuffer append(String s) Returns the current object with the String parameter s appended to the end. StringBuffer insert(int index, char c) StringBuffer insert(int index, String s) Inserts the character c (or String s) into the current StringBuffer object at index index. The characters (after index) are shifted to right. StringBuffer sb = new StringBuffer(“abcd”); sb.insert(0,”AB”)  sb is “ABabcd” sb.insert(1,”CD”)  sb is “ACDBabcd” sb.insert(8,”EFG”)  sb is “ACDBabcdEFG” sb.append(“HI”)  sb is “ACDBabcdEFGHI” CS101 - Algorithms & Programming I

  29. Palindrome Example import java.io.*; public class Palindrome { static boolean isPalindrome(String s) { int i = 0; int j = s.length() - 1; boolean flag = true; while ((i<j) && flag){ if (s.charAt(i) != s.charAt(j)) flag = false; else {i++; j--; } } return flag; } CS101 - Algorithms & Programming I

  30. Palindrome Example (cont.) public static void main(String args[]) throws IOException { String s; Scannerscan = new Scanner(System.in); System.out.print("A String > "); s = scan.nextLine(); if (isPalindrome(s)) System.out.println(s + " is a palindrome"); else System.out.println(s + " is not a palindrome"); } } CS101 - Algorithms & Programming I

  31. Decimal to Binary -- Example import java.util.*; public class DecToBinary { static StringBuffer toBinary(int decVal) { StringBuffer sb = new StringBuffer(""); if (decVal == 0) sb.insert(0,"0"); else while (decVal != 0) { if (decVal%2 == 0) sb.insert(0,"0"); else sb.insert(0,"1"); decVal = decVal / 2; } return sb; } CS101 - Algorithms & Programming I

  32. Decimal to Binary – Example (cont.) public static void main(String args[]) { int num; Scannerscan = new Scanner(System.in); System.out.print("An integer > "); num = scan.nextInt() System.out.println("Decimal Number: " + num + " Corresponding Binary Number: " + toBinary(num)); } } CS101 - Algorithms & Programming I

  33. Searching • Search the first n elements of x for a target value & return its location if found, else -1 public static int search(int n, int[] x, int target) { int pos = 0; while ( pos < n && x[pos] != target) pos++; if ( x[pos] == target) return pos; // found at pos else return –1; // not found } Sequential search O(n) CS101 - Algorithms & Programming I

  34. 5 4 1 7 3 9 5 4 1 3 7 9 3 4 1 5 7 9 3 1 4 5 7 9 1 3 4 5 7 9 n=6 n=5 n=4 n=3 n=2 n=1 + + + + + Sorting • Selection sort 5 9 1 7 3 4 Sum = n.( n +1) / 2 = n2/2 + n/2 O( n2) CS101 - Algorithms & Programming I

  35. tmp 5 0 1 9 1 2 7 3 4 3 grades Selection Sort • To sort first n elements of array X while n > 1 find location of max value in first n elements of X swap element at location of max with element at n-1 decrement n swap( int i, int j) { int tmp; tmp = X[i]; X[i} = X[j]: X[j] = tmp; } 9 3 9 CS101 - Algorithms & Programming I

More Related