1 / 23

Java Strings & Arrays Lecture Notes

Learn about strings and arrays in Java, including creation, access, copying, storage, indexing, multidimensional arrays, and string methods.

Download Presentation

Java Strings & Arrays Lecture Notes

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. MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel University at Albany, SUNY Fall 2004

  2. Outline for the ClassArrays • Recap • Strings • Arrays • Creation and Access • Copying & assigning arrays • Storage & Indexing • Multidimensional Array • Examples

  3. Strings

  4. Objects and ClassesStandard 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.

  5. Objects and ClassesString 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.

  6. Objects and ClassesStandard 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; } 

  7. Creating ClassesThe 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”))

  8. Creating ClassesThe 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”) ;

  9. Creating ClassesThe 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?

  10. Arrays

  11. ArraysIntroduction • 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

  12. ArraysStorage 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:

  13. ArraysMemory 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.

  14. ArraysArray 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]

  15. ArraysArray 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

  16. ArraysArray 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]

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

  18. ArraysLength 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.

  19. ArraysPassing 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 • The contents of the array are modified • The main program sees the changes to the array • show using stack • The array is assigned to another array in the method • No change happens in the calling method  show using stack

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

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

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

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

More Related