MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel University at Albany, SUNY Fall 2004 Sanjay Goel, School of Business, University at Albany, SUNY 1 Outline for the Class Arrays • Recap • Strings • Arrays – – – – Creation and Access Copying & assigning arrays Storage & Indexing Multidimensional Array • Examples Sanjay Goel, School of Business, University at Albany, SUNY 2 Strings Sanjay Goel, School of Business, University at Albany, SUNY 3 Objects and Classes Standard Classes: String • • • String class represents character strings All string literals in Java programs are implemented as instances of this class, e.g. “abc” String class includes methods for – – – – – Examining individual characters of the sequence Comparing strings Searching strings Extracting substrings Creating a copy of a string with upper or lower case translation. Sanjay Goel, School of Business, University at Albany, SUNY 4 Objects and Classes String Methods • String class has following methods – – – – – – – – – – – boolean equals(Object anObject) Compares this string with another int length() Gets length of string char charAt(int index) Returns char at index pos. in string int compareTo(String str) Returns an integer based on lexigographic order int indexOf(in ch) Gets position of character in string (-1 if not present) int indexOf(String str) Gets position of first letter of str in the string String concat(String str) Concatenates two strings and returns String toLowerCase() Converts to lower case String toUpperCase() Converts to upper case char[] toCharArray() Returns character array static String valueof(type prim) Converts primitive to string. Sanjay Goel, School of Business, University at Albany, SUNY 5 Objects and Classes Standard Classes: Palindrome static boolean isPalindrome(String s) { int left = 0; int right = s.length() – 1; while (left < right) { if (s.charAt(left) != s.charAt(right)) return false; left++; right--; } return true; } Sanjay Goel, School of Business, University at Albany, SUNY 6 Creating Classes The equals Method • Definition – Returns true if the strings are the same and false if they differ. – As soon as a character in one string is not equal to the corresponding character in the second string, the comparison is terminated and the condition returns to false. • Syntax • Example – (strName.equals(strInput)) (strName.equals(“Bill”)) Sanjay Goel, School of Business, University at Albany, SUNY 7 Creating Classes The equalsIgnoreCase Method • Definition – Is similar to the equals method but does not differentiate between uppercase and lowercase. • Syntax • Example – String strName = new String(“Joan”) ; String strName2 = new String(“JOAN”) ; Sanjay Goel, School of Business, University at Albany, SUNY 8 Creating Classes The compareTo Method • Definition – Used to determine less than or greater than. – Returns an integer with one of three possible values. • Syntax • Example – String strWord = new String(“Hope”) ; String strWord2 = new String(“Hopeless”) ; //Compare the strings if (strWord.compareTo(strWord2 < 0) //Display a message - - What will it be? Sanjay Goel, School of Business, University at Albany, SUNY 9 Arrays Sanjay Goel, School of Business, University at Albany, SUNY 10 Arrays Introduction • When do we need arrays? – When we have large data sets of the same type – e.g. test scores of the students or prime numbers between 0 and 100. – It is cumbersome to define a separate variable for each value. – Allows you to define one single variable and just put multiple values in • An array in Java is a container that holds a related group of values of the same type. – The elements in an array are ordered are numbered 0 through n-1 – where n is the number of individual elements in the array. • The position of an element in an array is called index of the array Sanjay Goel, School of Business, University at Albany, SUNY 11 Arrays Storage in Memory • Before we even start let us understand how memory is organized and how data is stored in memory. – Each location in memory has a unique address. • Data: 0 1 2 3 4 5 Sanjay Goel, School of Business, University at Albany, SUNY 12 Arrays Memory Pointers • This means that the memory location where the array points does not contain array data rather it contains a reference or a pointer to the actual array data. – When you declare an array you just create a pointer which points to nothing. – To find the address in memory of a specific element, the computer can add the element’s index to the address of the location of the first element. Sanjay Goel, School of Business, University at Albany, SUNY 13 Arrays Array Declaration and Memory Allocation • This is a two step process: • Array Declaration – You declare array variables just like any other variable by specifying the type followed by the name of the variable. – variableType [] variableName; – int [] myArray; • Memory Allocation – To actually create an array you have to use new. • arrayName = new arrayType[length] – length is an integer expression – e.g. myArray = new int[10] Sanjay Goel, School of Business, University at Albany, SUNY 14 Arrays Array Length • You can do both things in a single step – arrayType arrayName = new arrayType[length] – Once an array is created it has a fixed size. – An array can be reassigned to point to a different array that has a different size Sanjay Goel, School of Business, University at Albany, SUNY 15 Arrays Array Indexing • Array Indexing – Once you declare an array. Each element can be accessed by using an index variable of integer type. The indexing is from 0 to n-1 for an array of length n. – arrayName[expr] • This expression is any integer expression – ith element of the array is represented as arrayName[i-1] Sanjay Goel, School of Business, University at Albany, SUNY 16 Arrays Assigning Arrays int [] a = new int[10]; a = new int[20]; or int [] a1 = {10, 20, 30} int [] a2 = {1, 2, 3, 4, 5} a1 = a2; // Now both a1 and a2 are pointing to same variable Sanjay Goel, School of Business, University at Albany, SUNY 17 Arrays Length of an Array • The length of the array is stored in a variable called length and can be accessed as: arrayName.length e.g. a.length; for (int i = 0; i < a.length. i++) { } • If you index past the end of the array you get an IndexOutOfBoundsException error. Sanjay Goel, School of Business, University at Albany, SUNY 18 Arrays Passing arrays to methods • Java passes parameters by value. • Arrays are reference types i.e. they store the address of the array location • So when we pass arrays as arguments a copy of the reference value (address) is passed to the method. • Two Scenarios 1. The contents of the array are modified a. The main program sees the changes to the array show using stack 2. The array is assigned to another array in the method a. No change happens in the calling method show using stack Sanjay Goel, School of Business, University at Albany, SUNY 19 Arrays Copying Arrays • You need to copy arrays element by element rather than just assigning one array to another. By just assigning one array name to another you are just copying pointers without copying the array. • If you want to create a new array from an old array you need to create a new array and assign all the values from the old array to the new array, e.g. static int[] duplicate(int[] a) { int[] theCopy = new int[a.length]; for(int I = 0; I < a.length; I++) { theCopy[I] = a[I]; } return theCopy; } a1 = duplicate(a2) • Cloning: For one-dim arrays java provides a cloning mechanism – i.e. a1 = (int[])a2.clone(); // built-in array copy Sanjay Goel, School of Business, University at Albany, SUNY 20 Arrays Types and Arrays • Similar to integer arrays you can have arrays in other primitive types and also classes. • Primitive Types – double [] d is an array of doubles – char [] c is an array of characters • Non-Primitive Types – String[] args is an array of Strings – Point[] points is an array of points • Show the example of sieve of eratosthenes • Show the example of character count Sanjay Goel, School of Business, University at Albany, SUNY 21 Arrays Multidimensional Array • Just like single dimensional arrays we have multi-dimensional arrays int[] a1; Row int[][] a2; Matrix int[][][] a3; 3D Grid • Declaring 2D arrays int[][] a2 = new int[expr1][expr2]; • Initializing 2D arrays int[][] a = {{1,2},{3,4},{5,6}}; // 3x2 int[][] b = {{1,2,3}, {4,5,6}}; // 2x3 int[][] c = {{1,2,3,4,5,6}}; // 1x3 int[][] ragged = {{1,2}, {3,4,5}, {6}} // 3 rows each with different # of elements Sanjay Goel, School of Business, University at Albany, SUNY 22 Arrays Examples • Sum of an array two different ways manually without using loops • Minimum and maximum of an array • Sieve of Eratosthenes • Example of Character Count • Sorting of arrays (selection sort) • Searching an ordered array • Algorithm Complexity – Sorting and Searching Sanjay Goel, School of Business, University at Albany, SUNY 23