Download presentation
Presentation is loading. Please wait.
1
© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter 8 - 1 Chapter 8 Characters and Strings
2
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 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.
3
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 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.
4
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 4 ASCII Table For example, character 'O' is 79 (row value 70 + col value 9 = 79). O 9 70
5
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 5 Character Processing Declaration and initialization char ch1, ch2 = ‘X’; Type conversion between int and char. messageBox.show("ASCII code of character X is " + (int) ' X ' ); message.show("Character with ASCII code 88 is " + (char)88 ); This comparison returns true because ASCII value of 'A' is 65 while that of 'c' is 99. ‘A’ < ‘c’
6
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 6 Let's Try #1, page 358
7
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 7 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 messageBox.show( “Hello, how are you?” );
8
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 8 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, String name1; name1 = new String( “Latte” ); But we normally use a shorthand, instead, treating String objects much like primitive data. For example, String name1; name1 = “Latte”; These two statements are equivalent. Only works for String
9
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 9 Accessing Individual Elements Individual characters in a String accessed with the charAt method. 012345 6 Sumatr a String name = “Sumatra”; name This variable refers to the whole string. name.charAt( 3 ) The method returns the character at position # 3.
10
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 10 Determining the Size We determine the number of characters in a String with the length method. String name = “Sumatra”, str1 = “one”, str2 = “”, str3; Error because no object is created for str3, so it is a null. name.length( ); str1.length( ); str2.length( ); str3.length( ); 7 3 0 Error!
11
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 11 Example: Counting Vowels 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.
12
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 12 Example: Counting Words 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 } Problem: Inner loops could cause index to become equal to numberOfCharacters, which is an error.
13
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 13 Example: Counting Words - 2 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 } Problem: wordCount will be one more than the actual count if the sentence ends with one or more spaces.
14
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 14 Example: Counting ‘Java’ 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++; } Continue reading words and count how many times the word Java occurs in the input, ignoring the case. Notice how the comparison is done. We are not using the == operator.
15
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 15 Other Useful String Operators MethodMeaning compareTo Compares the two strings. str1.compareTo( str2 ) substring Extracts the a substring from a string. str1.substring( 1, 4 ) trim Removes the leading and trailing spaces. str1.trim( ) valueOf Converts a given primitive data value to a string. String.valueOf( 123.4565 ) startsWith Returns true if a string starts with a specified prefix string. str1.startsWith( str2 ) endsWith Returns true if a string ends with a specified suffix string. str1.endsWith( str2 ) See the String class documentation for details.
16
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 16 Let's Try #1, page 369
17
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 17 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. byte short int double long float boolean String Applet MessageBox HiLo InputBox etc. char primitive reference Data Type
18
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 18 Effect of Assignment on Primitives Code State of Memory int num1, num2; num1 = 14; num2 = num1; num1 += 5; int num1, num2; num1 = 14; num2 = num1; num1 += 5; After is executed A A num1 num2 14 A A B B After is executed B B num1 num2 19 14
19
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 19 str Memory Allocation for Reference Data Type Code State of Memory String str; str = “Jakarta”; 2036 J 2040 2044 2048 a k a r t a We assume four bytes to a row, so each row has two characters (16 bits per char). 2036 This value 2036 is the address where the string is actually stored. str is a variable of type String, a reference data type, so the content is an address (i.e. reference).
20
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 20 Effect of Assignment on References - 1 Code State of Memory String word1, word2; word1 = new String( “Java” ); word2 = word1; A A Both word1 and word2 are allocated memory (to store references), but the objects themselves are not yet created, so they both contain null. word1 word2 After is executed A A
21
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 21 word1 word2 Effect of Assignment on References - 2 Code State of Memory String word1, word2; word1 = new String( “Java” ); word2 = word1; B B One String object is created and assigned to word1, so word1 contains the address of this object. word1 word2 After is executed B B String Java
22
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 22 word1 word2 String Java Effect of Assignment on References - 3 Code State of Memory String word1, word2; word1 = new String( “Java” ); word2 = word1; C C Content of word1, which is an address, is assigned to word2, making word2 refer to the same object. word1 word2 String Java After is executed C C
23
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 23 Equality (==) vs. equals—Case 1 word1 word2 String Java word1 == word2 word1.equals( word2 ) true word1 and word2 point to the same object.
24
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 24 Equality (==) vs. equals—Case 2 word1 word2 String Java word1 == word2 word1.equals( word2 ) true false String Java word1 and word2 point to different objects having the same string.
25
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 25 Equality (==) vs. equals—Case 3 word1 word2 String Java word1 == word2 word1.equals( word2 ) false String Bali word1 and word2 point to different objects with different strings.
26
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 26 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.
27
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 27 Sample StringBuffer Processing - 1 Replace all vowels in the sentence with ‘X’. 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 );
28
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 28 Sample StringBuffer Processing - 2 Creates a sentence with words having even number of letters. Stop when the input word is STOP. 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.
29
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 29 Let's Try #1, page 384
30
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 30 Passing Objects to Methods - 1 Code State of Memory //StringBuffer word is //created here tester.myMethod( word ); public void myMethod( StringBuffer strBuf ) { strBuf.setCharAt( 0, ‘Y’ ); } A A A. A. Local variables do not exist before the method execution At before myMethod A A word StringBuffer Java
31
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 31 B. B. The value of the argument, which is an address, is copied to the parameter. At before myMethod A A word StringBuffer Java Code State of Memory //StringBuffer word is //created here tester.myMethod( word ); public void myMethod( StringBuffer strBuf ) { strBuf.setCharAt( 0, ‘Y’ ); } Passing Objects to Methods - 2 B B Values are copied at B B StringBuffer Java word strBuf
32
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 32 C. C. The content of the object referenced by strBuf is changed. StringBuffer Java word strBuf Code State of Memory //StringBuffer word is //created here tester.myMethod( word ); public void myMethod( StringBuffer strBuf ) { strBuf.setCharAt( 0, ‘Y’ ); } Passing Objects to Methods - 3 After is executed C C StringBuffer Yava word strBuf C C
33
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 33 StringBuffer Yava word strBuf D. D. The parameter is erased. The argument still points to the same (now modified) object. Code State of Memory //StringBuffer word is //created here tester.myMethod( word ); public void myMethod( StringBuffer strBuf ) { strBuf.setCharAt( 0, ‘Y’ ); } Passing Objects to Methods - 4 D D StringBuffer Yava word At after myMethod D D
34
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 34 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.
35
© 2000 McGraw-HillIntroduction to Object-Oriented Programming with Java--WuChapter 8 - 35 Exercise #5 Write a loop that prints out a user's input string in reverse. If someone enters Hello Your program outputs olleH Just use the System.out for your output. No need to get fancy.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.