1 / 35

Chapter 8

Chapter 8. Characters and Strings. Chapter 8 Objectives. After you have read and studied this chapter, you should be able to Declare and manipulate data of the char data type. Write string processing programs using String and StringBuffer objects.

neo
Download Presentation

Chapter 8

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. Chapter 8 Characters and Strings Introduction to Object-Oriented Programming with Java--Wu

  2. Chapter 8 Objectives After you have read and studied this chapter, you should be able to • Declare and manipulate data of the char data type. • Write string processing programs using String and StringBuffer objects. • Differentiate the String and StringBuffer classes and use the correct class in solving a given task. • Distinguish the primitive and reference data types and show how the memory allocation between the two is different. • Tell the difference between equality and equivalence testings for String objects. • Show, by using the state-of-memory diagrams, how objects are passed to methods and returned from methods. Introduction to Object-Oriented Programming with Java--Wu

  3. Characters • In Java single characters are represented using the data type char. Character constants are written as symbols enclosed in single quotes, for example, 'a', 'X', and '5'. • To represent characters in computer, U. S. computer manufacturers devised several coding schemes. • One coding scheme widely used today is ASCII (American Standard Code for Information Interchange). • To accommodate the character symbols of non-English languages, the Unicode Consortium established the Unicode Worldwide Character Standard, commonly known as Unicode. Introduction to Object-Oriented Programming with Java--Wu

  4. 9 For example, character 'O' is 79 (row value 70 + col value 9 = 79). O 70 ASCII Table Introduction to Object-Oriented Programming with Java--Wu

  5. Declaration and initialization char ch1, ch2 = ‘X’; messageBox.show("ASCII code of character X is " + (int) 'X' ); message.show("Character with ASCII code 88 is " + (char)88 ); Type conversion between int and char. ‘A’ < ‘c’ This comparison returns true because ASCII value of 'A' is 65 while that of 'c' is 99. Character Processing Introduction to Object-Oriented Programming with Java--Wu

  6. messageBox.show( “Hello, how are you?” ); Strings • A string is a sequence of characters that is treated as a single value. • The String data type is used to represent strings in Java. • We have been using String objects all along. For example, to display a text with messageBox, we write Introduction to Object-Oriented Programming with Java--Wu

  7. String name1; name1 = new String( “Latte” ); String name1; name1 = “Latte”; These two statements are equivalent. String is an Object • String is a class in the java.lang package. • Because String is a class, we need to create an instance of String in Java for string processing. Like any other objects, we need a declaration and object creation for the instances of the String class. For example, But we normally use a shorthand, instead, treating String objects much like primitive data. For example, Introduction to Object-Oriented Programming with Java--Wu

  8. 0 1 2 3 4 5 6 S u m a t r a String name = “Sumatra”; name.charAt( 3 ) name The method returns the character at position # 3. This variable refers to the whole string. Accessing Individual Elements • Individual characters in a String accessed with the charAt method. Introduction to Object-Oriented Programming with Java--Wu

  9. 7 3 0 Error! name.length( ); str1.length( ); str2.length( ); str3.length( ); String name = “Sumatra”, str1 = “one”, str2 = “”, str3; Determining the Size • We determine the number of characters in a String with the length method. Error because no object is created for str3, so it is a null. Introduction to Object-Oriented Programming with Java--Wu

  10. char letter; String name = inputBox.getString("What is your name?"); int numberOfCharacters = name.length(); int vowelCount = 0; for (int i = 0; i < numberOfCharacters; i++) { letter = name.charAt(i); if ( letter == 'a' || letter == 'A' || letter == 'e' || letter == 'E' || letter == 'i' || letter == 'I' || letter == 'o' || letter == 'O' || letter == 'u' || letter == 'U' ) { vowelCount++; } } messageBox.show(name + ", your name has " + vowelCount + " vowels"); Here’s the code to count the number of vowels in the input string. Example: Counting Vowels Introduction to Object-Oriented Programming with Java--Wu

  11. String sentence = inputBox.getString("Enter a sentence:"); int numberOfCharacters = sentence.length(); int index = 0; int wordCount = 0; while (index < numberOfCharacters ) { //ignore blank spaces while (sentence.charAt(index) == ' ') { index++; } //now locate the end of the word while (sentence.charAt(index) != ' ') { index++; } wordCount++; //another word found, so increment the counter } Example: Counting Words Problem: Inner loops could cause index to become equal to numberOfCharacters, which is an error. Introduction to Object-Oriented Programming with Java--Wu

  12. String sentence = inputBox.getString("Enter a sentence:"); int numberOfCharacters = sentence.length(); int index = 0; int wordCount = 0; while (index < numberOfCharacters ) { //ignore blank spaces while (index < numberOfCharacters && sentence.charAt(index) == ' ') { index++; } //now locate the end of the word while (index < numberOfCharacters && sentence.charAt(index) != ' ') { index++; } wordCount++; //another word found, so increment the counter } Example: Counting Words - 2 Problem: wordCountwill be one more than the actual count if the sentence ends with one or more spaces. Introduction to Object-Oriented Programming with Java--Wu

  13. int javaCount = 0; boolean repeat = true; String word; while ( repeat ) { word = inputBox.getString("Next word:"); if ( word.equals("STOP") ) { repeat = false; } else if ( word.equalsIgnoreCase("Java") ) { javaCount++; } } Notice how the comparison is done. We are not using the == operator. Example: Counting ‘Java’ Continue reading words and count how many times the word Java occurs in the input, ignoring the case. Introduction to Object-Oriented Programming with Java--Wu

  14. Other Useful String Operators • See the String class documentation for details. Introduction to Object-Oriented Programming with Java--Wu

  15. Data Type reference primitive long String byte short Applet MessageBox double char InputBox int HiLo boolean etc. float Primitive versus Reference Types • Data types are classified into two groups: primitive and reference. • Nonnumerical data types char and boolean and all of the numerical data types ae primitive. • All of the objects you have learned so far are reference data types. Introduction to Object-Oriented Programming with Java--Wu

  16. int num1, num2; num1 = 14; num2 = num1; num1 += 5; int num1, num2; num1 = 14; num2 = num1; num1 += 5; A B After is executed After is executed B A num1 num1 19 14 num2 num2 14 14 Effect of Assignment on Primitives Code State of Memory Introduction to Object-Oriented Programming with Java--Wu

  17. String str; str = “Jakarta”; str is a variable of type String, a reference data type, so the content is an address (i.e. reference). This value 2036 is the address where the string is actually stored. str 2036 J a 2036 2040 k a We assume four bytes to a row, so each row has two characters (16 bits per char). 2044 r t 2048 a Memory Allocation for Reference Data Type Code State of Memory Introduction to Object-Oriented Programming with Java--Wu

  18. A String word1, word2; word1 = new String( “Java” ); word2 = word1; After is executed A word1 word2 Effect of Assignment on References - 1 Code Both word1 and word2 are allocated memory (to store references), but the objects themselves are not yet created, so they both contain null. State of Memory Introduction to Object-Oriented Programming with Java--Wu

  19. B String word1, word2; word1 = new String( “Java” ); word2 = word1; After is executed B word1 word1 word2 word2 String Java Effect of Assignment on References - 2 Code One String object is created and assigned to word1, so word1 contains the address of this object. State of Memory Introduction to Object-Oriented Programming with Java--Wu

  20. C String word1, word2; word1 = new String( “Java” ); word2 = word1; After is executed C word1 word1 word2 word2 String String Java Java Effect of Assignment on References - 3 Code Content of word1, which is an address, is assigned to word2, making word2 refer to the same object. State of Memory Introduction to Object-Oriented Programming with Java--Wu

  21. word1 word2 String true Java true Equality (==) vs. equals—Case 1 word1 and word2 point to the same object. word1 == word2 word1.equals( word2 ) Introduction to Object-Oriented Programming with Java--Wu

  22. String String false Java Java true Equality (==) vs. equals—Case 2 word1 word2 word1 and word2 point to different objects having the same string. word1 == word2 word1.equals( word2 ) Introduction to Object-Oriented Programming with Java--Wu

  23. String String false Java Bali false Equality (==) vs. equals—Case 3 word1 word2 word1 and word2 point to different objects with different strings. word1 == word2 word1.equals( word2 ) Introduction to Object-Oriented Programming with Java--Wu

  24. StringBuffer • A String object is immutable, which means that once a String object is created, we cannot change it. • We can read individual characters in a string, but we cannot add, delete, or modify characters of a String object. • Remember that the methods of the String class, such as toUpperCase and substring, do not modify the original string; they return a new string. • Java adopts this immutability restriction to implement an efficient memory allocation scheme for managing String objects. • Creating a new string from the old one will work for most cases, but sometimes manipulating the content of a string directly is more convenient. • Manipulation here means operations such as replacing a character, appending a string with another string, deleting a portion of a string, and so forth. Introduction to Object-Oriented Programming with Java--Wu

  25. char letter; String inSentence = inputBox.getString("Enter a sentence:"); StringBuffer tempStringBuffer = new StringBuffer(inSentence); int numberOfCharacters = tempStringBuffer.length(); for (int index = 0; index < numberOfCharacters; index++) { letter = tempStringBuffer.charAt(index); if ( letter == 'a' || letter == 'A' || letter == 'e' || letter == 'E' || letter == 'i' || letter == 'I' || letter == 'o' || letter == 'O' || letter == 'u' || letter == 'U' ) { tempStringBuffer.setCharAt(index,'X'); } } messageBox.show( tempStringBuffer ); Sample StringBuffer Processing - 1 • Replace all vowels in the sentence with ‘X’. Introduction to Object-Oriented Programming with Java--Wu

  26. boolean repeat = true; String word; StringBuffer tempStringBuffer = new StringBuffer(""); while ( repeat ) { word = inputBox.getString("Next word:"); if ( word.equals("STOP") ) { repeat = false; } else if ( word.length() % 2 == 0 ) { tempStringBuffer.append(word + " "); } } Append word and a space to tempStringBuffer. Sample StringBuffer Processing - 2 • Creates a sentence with words having even number of letters. Stop when the input word is STOP. Introduction to Object-Oriented Programming with Java--Wu

  27. A At before myMethod A word StringBuffer Java Passing Objects to Methods - 1 Code public void myMethod( StringBuffer strBuf ) { strBuf.setCharAt( 0, ‘Y’ ); } //StringBuffer word is //created here tester.myMethod( word ); A. Local variables do not exist before the method execution State of Memory Introduction to Object-Oriented Programming with Java--Wu

  28. B At before myMethod A Values are copied at B word word strBuf StringBuffer StringBuffer Java Java Passing Objects to Methods - 2 Code public void myMethod( StringBuffer strBuf ) { strBuf.setCharAt( 0, ‘Y’ ); } //StringBuffer word is //created here tester.myMethod( word ); B. The value of the argument, which is an address, is copied to the parameter. State of Memory Introduction to Object-Oriented Programming with Java--Wu

  29. C After is executed C word word strBuf strBuf StringBuffer StringBuffer Java Yava Passing Objects to Methods - 3 Code public void myMethod( StringBuffer strBuf ) { strBuf.setCharAt( 0, ‘Y’ ); } //StringBuffer word is //created here tester.myMethod( word ); C. The content of the object referenced by strBuf is changed. State of Memory Introduction to Object-Oriented Programming with Java--Wu

  30. D At after myMethod D word word strBuf StringBuffer StringBuffer Yava Yava Passing Objects to Methods - 4 Code public void myMethod( StringBuffer strBuf ) { strBuf.setCharAt( 0, ‘Y’ ); } //StringBuffer word is //created here tester.myMethod( word ); D. The parameter is erased. The argument still points to the same (now modified) object. State of Memory Introduction to Object-Oriented Programming with Java--Wu

  31. Returning an Object from Methods • “Passing an object as an argument to a method” means passing the address of the object to the method. • The previous four slides illustrate the effect of passing an object to a method. • The same rule applies when we “return an object from a method.” It means the address of the object is passed back from the method. Introduction to Object-Oriented Programming with Java--Wu

  32. Sample Program: Eggy-Peggy • Problem Statement Write an application that will play the Eggy-Peggy word play with the user. The program will convert a string given by the user to a new string by placing the word “egg” in front of all vowels in the given string. • Major Tasks while ( the user wants to play ) { Task 1: get a string from the user; Task 2: generate a new eggy-peggy string; Task 3: display the result; } Introduction to Object-Oriented Programming with Java--Wu

  33. Eggy-Peggy – Design Introduction to Object-Oriented Programming with Java--Wu

  34. Eggy-Peggy – Object Diagram Introduction to Object-Oriented Programming with Java--Wu

  35. Eggy-Peggy Game – Development Steps • Start with a program skeleton. Define the EggyPeggyMain and EggyPeggy classes. • Add code to do the input and output routines. • Add code to play an Eggy-Peggy game. • Finalize the code by removing temporary statements and tying up loose ends. The End Introduction to Object-Oriented Programming with Java--Wu

More Related