Java i lecture_12_upd1

  • 113 views
Uploaded on

 

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
113
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
10
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Java I--Copyright © 2000 Tom Hunter
  • 2. Java I--Copyright © 2000 Tom HunterChapter 10Strings and Characters
  • 3. Java I--Copyright © 2000 Tom HunterCreatingandWorking with Strings
  • 4. Java I--Copyright © 2000 Tom Hunter• Strings are one of the first aspects of Java we learned.• We thought we knew Strings and how they worked.• In fact, Strings do a lot of things we have not beenaware of..Creating and Working with Strings
  • 5. Java I--Copyright © 2000 Tom Hunter• TypicalCertificationquestion:Creating and Working with Stringspublic class Test{public static void main( String[] args ){String w = “Welcome to “;String j = “Java “;float v = 1.2f;String txt;txt = w + j + v + “.”;System.out.println( txt );}}Welcome to Java 1.2.35Question:How many String variables are referenced here?How many blocks of character storage are allocated?15234
  • 6. Java I--Copyright © 2000 Tom HunterCreating and Working with Stringspublic class Test{public static void main( String[] args ){String w = “Welcome to “;String j = “Java “;float v = 1.2f;String txt;txt = w + j + v + “.”;System.out.println( txt );}}• Why does such atiny program needso many areas ofmemory?• Let’s explore the answer to thatquestion in detail:
  • 7. Java I--Copyright © 2000 Tom HunterCreating and Working with Strings• Recall from Lecture 1 that all Java characters arestored in 16-bit Unicode, so they are able to storeinternational character sets.• In Unicode, every character requires 2 bytes.Under this system, “Hello, world.”would require 26 bytes to store in memory.
  • 8. Java I--Copyright © 2000 Tom HunterCreating and Working with Strings• We know how to create Strings:String myname = “Joe”;//initialized to JoeorString myname = new String(“Joe” );// initialized to Joe• The bottom method is less familiar, but more correctunder the Object-Oriented method.• The top method is a convenience we use in order tomake String manipulation easier.
  • 9. Java I--Copyright © 2000 Tom HunterCreating and Working with Strings• Another convenience is in String concatenation:String a = “hello ”;String b = “world”;String c;c = a + b;• We accept that we’re not arithmetically adding thesetwo Strings.• Rather, the plus [ + ] operator has been overloaded.“Overloading” is when something has a differentmeaning depending on its context.
  • 10. Java I--Copyright © 2000 Tom HunterCreating and Working with Strings• When we do this:c = a + b;… it seems like we are really doing this:c = a.concat( b );( In fact, secretly, we’re using another class called aStringBuffer, which we’ll get to a little later.)
  • 11. Java I--Copyright © 2000 Tom HunterCreating and Working with Strings• Take the following example, where we areconcatenating a String a with an int i:String a = “Ten ”;int i = 4;String c ;c = a + i; Since i is being “added” to aString, the compiler knows it needsto convert i to a String also.The compiler creates a new Stringblock just to hold the convertedinteger.
  • 12. Java I--Copyright © 2000 Tom HunterCreating and Working with Stringsc = a + i;• Anytime you concatenate a String with another type,the other type is first converted into a String and then thetwo are concatenated. Really, this is done using methodtoString()which every object inherits from Objectc = a.concat( (String) b );
  • 13. Java I--Copyright © 2000 Tom HunterCreating and Working with Strings• If you concatenate other primitive data types with a String,it has a similar effect:String a = “”;boolean b = false;String c =“Microsoft isdishonest=”;a = c + b;Microsoft isdishonest=false
  • 14. Java I--Copyright © 2000 Tom HunterCreating and Working with Strings• The += operator is also overloaded:String c = “Microsoft “;String b = “rules”;c += b;{ c == “Microsoft rules” }
  • 15. Java I--Copyright © 2000 Tom HunterCreating and Working with Strings• The following example is a crackerjack Certificationquestion:String a = ““;int b = 2;int c = 3;a = b + c;• True or False: the above statement is a Syntax error:True, this isis a syntax error. To force theconversion to String, at least one of theoperands on the + sign must be a String.
  • 16. Java I--Copyright © 2000 Tom HunterCreating and Working with Strings• What about this example, where we’re concatenating a Stringobject to a regular object. What happens here?String a = “”;String b = “Test“;Employee e = new Employee(“GW”,”Bush”);a = b + e;• This still produces a String, and is equivalent to:a = b + e.toString();
  • 17. Java I--Copyright © 2000 Tom HunterCreating and Working with Strings• Class String is located at thetop of the class hierarchy.• The class is declared asfinal, which means itcannot be Subclassed,cannot be a Superclass toany Subclass.
  • 18. Java I--Copyright © 2000 Tom HunterCreating and Working with Strings• Class String contains 48 methods.• These methods allow you to do many things with aString object—except changechange the String, that is.• You can do anything with a String except change thatString.
  • 19. Java I--Copyright © 2000 Tom HunterCreating and Working with Strings• There are many methods that take a String argumentand return a String• None of these allow you to change the original String .• These methods may appear to change the String, but theydon’t. They merely return a different String.• Once a String object is instantiated, it can never bechanged. NeverNever.
  • 20. Java I--Copyright © 2000 Tom HunterCreating and Working with Strings• Strings are immutable.• That means, once they are created, they can’t bechanged.• Because String objects are immutable they can be shared.
  • 21. Java I--Copyright © 2000 Tom HunterCreating and Working with Strings• Here we have three String objects, a, b and c, whichhappen to contain identical Strings.String a = “hello”;String b = “hello”;String c = “hello”;• Because they are identical, the Java compiler only storesone copy of the String “hello”.• a, b and c are merely pointers to the same space.
  • 22. Java I--Copyright © 2000 Tom Hunterab “hello”cCreating and Working with Strings• Once the compiler discovers that the String object is thesame for all three, it uses the same String for all three.• Remember, a String can’t be changed!
  • 23. Java I--Copyright © 2000 Tom HunterCreating and Working with Strings• In this example, we are reassigning a reference, ormaking it point to a different place.• We’re not changing the String:String a = “hello”;String b = “hi”;String c;c = a;c = b;
  • 24. Java I--Copyright © 2000 Tom Hunter• This helps explain what is happening when we comparetwo Strings in this manner: if( a == b )• We are comparing the references, notnot the objects.a “hello”cb “hi”Creating and Working with Strings: Memory Leaksc = a;c = b;
  • 25. Java I--Copyright © 2000 Tom Hunter• Question: What happens to “ParsleySage” and“SageRosemary” after the reassignment?a = p + s;ParsleySageRosemaryThymeString p = new String( “Parsley” );String s = new String( “Sage” );String r = new String( “Rosemary” );String t = new String( “Thyme” );String a;ParsleySageaSageRosemarya = s + r;a = p + s + r;ParsleySageRosemary
  • 26. Java I--Copyright © 2000 Tom Hunter• In another language,such as C or C++, this would leadto the situation known as amemory leak, whenun-referenced objectsclutter up the RAMand the memorycannot be reclaimed.• Answer: Before today, you would have looked at theassignments a = p + s; and a = s + r;and thought that a had been changed.ParsleySageSageRosemaryParsleySageRosemarya• Now, you know. The objects “ParsleySage” and“SageRosemary” were really abandoned.
  • 27. Java I--Copyright © 2000 Tom HunterStrings: Garbage Collection• Having battled with C/C++ memory leaks, Jim Goslinghad the foresight to include Garbage Collection in Java,specifically to avoid memory leaks.
  • 28. Java I--Copyright © 2000 Tom HunterLengthofaString
  • 29. Java I--Copyright © 2000 Tom HunterLength of a String• To find out the length of a String—or the number ofcharacters a String has—you use the String’s methodlength():String a = “Testing”;int x = 0;x = a.length(); {x == 7}! Bonehead Alert !To find the length of an arrayarray object, you use theproperty length. (Notice, it’s not a method!)To find the length of a StringString object , you use themethod length(). Watch out!
  • 30. Java I--Copyright © 2000 Tom HunterSub-Strings
  • 31. Java I--Copyright © 2000 Tom HunterSub-Strings• You can extract a substring from a larger String objectwith the substring() method of class String.String greet = “Howdy”;String s = greet.substring( 0, 4 );Howdy0 1 2 3 4The first argument 0,is the 1st characterof the substring thatyou dodo want to copy.The 4 is the 1stcharacter that youdon’tdon’t want to copy.So...{s is equal to “Howd”}
  • 32. Java I--Copyright © 2000 Tom HunterFindingIndividualCharacters:charAt()
  • 33. Java I--Copyright © 2000 Tom HunterFinding Individual Characters: charAt()• The String function charAt() allows you to discoverand return the character at a certain point in a String.String a = “Testing”;char b = ‘ ’;b = a.charAt( 3 );{ b == ‘t’} Testing0 1 2 3 4 5 6
  • 34. Java I--Copyright © 2000 Tom HunterComparingStrings
  • 35. Java I--Copyright © 2000 Tom HunterComparing Strings equals()• You now know you cannot compare the references oftwo String objects in order to determine if the referencedobjects are equal.• You accomplish that goal using the equals() methodof class String.String a = “hello”;String b = “hello”;a.equals( b );
  • 36. Java I--Copyright © 2000 Tom HunterComparing Strings equals()• In fact, you can even take a shortcut to the samecompare:String b = “hello”;“hello”.equals( b );
  • 37. Java I--Copyright © 2000 Tom HunterComparing Strings equalsIgnoreCase()• In fact, you can even take a shortcut to the samecompare:String b = “HELLO”;“hello”.equalsIgnoreCase( b );
  • 38. Java I--Copyright © 2000 Tom HunterMethodreplace()
  • 39. Java I--Copyright © 2000 Tom HunterComparing Strings replace()• Remember, this does not change the original, it return anew String object in which the changes have been made.String b = “hacker heaven”;String n = “”;n = b.replace( ‘h’, ‘H’ );
  • 40. Java I--Copyright © 2000 Tom HunterMethodtrim()
  • 41. Java I--Copyright © 2000 Tom HunterComparing Strings trim()• This method merely removes any extra spaces fromboth the front and back of a String.String b = “ hacker heaven ”;String n = “”;n = b.trim();{ n == “hacker heaven” }• Note: this does not alter the original String.• Rather, it returns a new String with theleading and trailing spaces omitted.
  • 42. Java I--Copyright © 2000 Tom HunterStringBufferClass
  • 43. Java I--Copyright © 2000 Tom HunterStringBuffer Class• An object of class String cannot be altered after ithas been created.• An object of class StringBuffer can be altered.• We describe the class StringBuffer as a mutablemutableclass, meaning it can be changed.• StringBuffer are used internally to implementmany of the methods in the String class.
  • 44. Java I--Copyright © 2000 Tom HunterStringBuffer Class• Every StringBuffer object can hold only a certainamount of characters.• A StringBuffer has a capacity that describes thenumber of characters it can hold.• This number is determined at the time of creation.
  • 45. Java I--Copyright © 2000 Tom HunterStringBuffer Class• If not specified when the it is instantiated, aStringBuffer has a default capacity of 16 characters.• Therefore, you generally specify the capacity when youinstantiate your StringBuffer .• We say a StringBuffer is Dynamically Resizable.
  • 46. Java I--Copyright © 2000 Tom HunterStringBuffer Class• A StringBuffer is instantiated as follows:StringBuffer d = new StringBuffer();(This one will begin with a capacity of 16 characters. )StringBuffer s = new StringBuffer( 100 );(This one will begin with a capacity of 100 characters. )
  • 47. Java I--Copyright © 2000 Tom HunterStringBuffer Class• This StringBuffer will contain 21 characters:StringBuffer e;e = new StringBuffer( “hello” );(This one has a capacity of 21 characters, because theinitializing String contains 5 characters.• Every StringBuffer starts off with 16 characters ofcapacity. When you initialize it with a String, you still get theoriginal 16, and your initializing String is just added to that16.
  • 48. Java I--Copyright © 2000 Tom HunterStringBuffer Class• If you add characters to your StringBuffer, it growsin size—it’s Dynamically Resizable.• You don’t worry about its size—it’s a question ofefficiency.
  • 49. Java I--Copyright © 2000 Tom HunterStringBuffer Class• For example, this StringBuffer would beinefficient:StringBuffer e;e = new StringBuffer( 99999999 );(This one will hold 99999999 characters.)
  • 50. Java I--Copyright © 2000 Tom HunterMethodappend()
  • 51. Java I--Copyright © 2000 Tom HunterStringBuffer Class: append()• If you do wish to add to your StringBuffer ,you use its append() method:StringBuffer e;e = new StringBuffer( 100 );e.append( “Key Largo” );• A StringBuffer makes your code run fasterbecause you create fewer new objects such astemporary Strings.
  • 52. Java I--Copyright © 2000 Tom HunterStringBuffer Class: append()• The method append() always adds the charactersto then end of the StringBuffer.• The method append() is overloaded 10 times.• append() takes arguments of every primitive datatype and will convert each to a String automatically.
  • 53. Java I--Copyright © 2000 Tom HunterStringBuffer Class• You cannot intermingle String methods withStringBuffer methods.• Attempts to mix the two present ripe opportunities forCertification exam questions—and the Final Exam.You Have Been Warned!
  • 54. Java I--Copyright © 2000 Tom HunterStringBuffer Class• When the overloaded plus sign [ + ] concatenates a Stringto something else, it uses a StringBuffer object:d = “Ten” + 4 + “ya”;• The above is actually implemented as follows:d=new StringBuffer().append(“Ten”).append(4).append(“ya”);• This is initially created with the defaultcapacity.
  • 55. Java I--Copyright © 2000 Tom HunterMethodinsert()
  • 56. Java I--Copyright © 2000 Tom HunterStringBuffer Class: insert()• Method append() is the principle way to addcharacters to the end of a StringBuffer.• StringBuffer method insert() is used to placecharacters into an existing StringBuffer object at aspecified location.• Method insert() is overloaded 9 times.
  • 57. Java I--Copyright © 2000 Tom Hunter• Whereas append() addstext to the end of theStringBuffer object, methodinsert() takes twoarguments.StringBuffer b;b = new StringBuffer( “start” );startb.append( “le” );b.insert( 4, “le” );startle0 1 2 3 4 5 6starlet• The first argument is an integer “offset” that tells thefirst character position to begin inserting the secondargument.• The second argument can be any data type.
  • 58. Java I--Copyright © 2000 Tom HunterMethodlength()
  • 59. Java I--Copyright © 2000 Tom HunterStringBuffer Class: length()• Classes String and StringBuffer do share a fewmethods.• You can learn the length of a StringBuffer byusing the method: length().
  • 60. Java I--Copyright © 2000 Tom HunterMethodcapacity()
  • 61. Java I--Copyright © 2000 Tom HunterStringBuffer Class: capacity()• Method length() tells you the amount of memory aStringBuffer currently is using.• Method capacity(), on the other hand, tells you thetotal amount of memory allocated to a StringBuffer.
  • 62. Java I--Copyright © 2000 Tom HunterMethodcharAt()
  • 63. Java I--Copyright © 2000 Tom Hunterchar x;StringBuffer j;j = new StringBuffer(“jumbled”);x = j.charAt( 3 );{ x == ‘b’ }StringBuffer Class: charAt()• You can retrieve the character at a particular indexwithin a StringBuffer (or a String, for thatmatter) by using the method:charAt() jumbled0 1 2 3 4 5 6
  • 64. Java I--Copyright © 2000 Tom HunterMethodsubstring()
  • 65. Java I--Copyright © 2000 Tom HunterString z;StringBuffer j;j = new StringBuffer(“jumbled”);x = j.substring( 2, 5 );{ z == ‘mbl’ }StringBuffer Class: substring()• You can retrieve a sequence of characters from aStringBuffer by using the method:substring()jumbled0 1 2 3 4 5 6The second argument is thecharacter after the end of thesubstring you want.
  • 66. Java I--Copyright © 2000 Tom HunterMethodreverse()
  • 67. Java I--Copyright © 2000 Tom HunterStringBuffer Class: reverse()• Method reverse() simply reverses the order of thecharacters in the StringBuffer.StringBuffer king;king = new StringBuffer( “murder” );king.reverse();{ king.toString() == “redrum” };
  • 68. Java I--Copyright © 2000 Tom HunterMethodensureCapacity()
  • 69. Java I--Copyright © 2000 Tom HunterStringBuffer Class: ensureCapacity()• Method ensureCapacity() simply makes sure thatyour StringBuffer has at least the capacity you specify.This is primarily an issue of efficiency.• One could say the argument of this method issomething called “Minimum capacity.”ensureCapacity( int minimumCapacity );
  • 70. Java I--Copyright © 2000 Tom HunterStringBuffer Class: ensureCapacity()• There is a twist on how you apply ensureCapacity()StringBuffer sb;sb = new StringBuffer(“Test”);• First (Certification-type question) What is the currentcapacity of StringBuffer object sb?20 = 16 + 4
  • 71. Java I--Copyright © 2000 Tom Hunter• Since we know sb has a current capacity of 20, let’stry a few experiments:StringBuffer sb;sb = new StringBuffer(“Test”);sb.ensureCapacity( 19 );StringBuffer Class: ensureCapacity()• What would be the capacity of sb after this statement?20 = 16 + 4original20
  • 72. Java I--Copyright © 2000 Tom HunterStringBuffer Class: ensureCapacity()• What would be the capacity of sb after this statement?StringBuffer sb;sb = new StringBuffer(“Test”);sb.ensureCapacity( 21 );• If you asked for less that was already allocated, nothingchanges.• However, if you asked to increase the allocation, it givesyou the largerlarger of two-times the original plus 2 OR yourrequest.42original20= 20*2 + 2
  • 73. Java I--Copyright © 2000 Tom HunterStringBuffer Class: ensureCapacity()• Finally, let’s test that:StringBuffer sb;sb = new StringBuffer(“Test”);sb.ensureCapacity( 43 );• Since this request is largerlarger than two-times the originalallocation, plus two, our request prevails.43original20
  • 74. Java I--Copyright © 2000 Tom HunterCharacterClass
  • 75. Java I--Copyright © 2000 Tom HunterCharacter Class• Most methods in the Class Character are Static.• Most of these methods take a character argument.• They perform either a test or a manipulation on thatargument.
  • 76. Java I--Copyright © 2000 Tom HunterMethodisDefined()
  • 77. Java I--Copyright © 2000 Tom HunterCharacter Class: isDefined()• This method seeks to know if the character that isprovided as an argument is defined in the Unicodecharacter set.int x = “}”;Character.isDefined( x );• true means the character is defined.
  • 78. Java I--Copyright © 2000 Tom HunterMethodisLetter()
  • 79. Java I--Copyright © 2000 Tom HunterCharacter Class: isLetter()• This method tries to determine if a character is analphabetic letter—of any language in the Unicodecharacter set—(watch out) or if it is not.int x = “t”;Character.isLetter( x );• true means the character is a letter.
  • 80. Java I--Copyright © 2000 Tom HunterMethodisDigit()
  • 81. Java I--Copyright © 2000 Tom HunterCharacter Class: isDigit()• This method tries to determine if a character is a digit.int x = “3”;Character.isLetter( x );• true means the character is a digit.
  • 82. Java I--Copyright © 2000 Tom HunterStringTokenizerClass
  • 83. Java I--Copyright © 2000 Tom HunterStringTokenizer Class• The StringTokenizer class is a tremendouslyuseful and tricky class that can be used to do things likebreak a String up into words.• What we call a “word”, the computer knows as a“Token”—or a unit of a String.• You will find this term is used commonly in otherlanguages also.
  • 84. Java I--Copyright © 2000 Tom HunterStringTokenizer Class• The item used to decide where one token ends andanother begins is called the delimiter.• Commonly, you choose the delimiter to be a:—space,—tab or—newline• Although these are the common delimiters, you get tochoose what you want to use for a delimiter.• In fact, a token can be many characters, not just one.
  • 85. Java I--Copyright © 2000 Tom HunterStringTokenizer Class• In fact, you can change the delimiter every time you calla method of the StringTokenizer class object.• When you use an object of class StringTokenizer ,there is one primary decision that has to be made.—was the returnTokens flag set totrue or false?
  • 86. Java I--Copyright © 2000 Tom HunterStringTokenizer Class: returnTokens• If the returnTokens flag is false, then thedelimiter characters only separate other tokens.• If the returnTokens flag is true, then thedelimiter characters are themselves tokens.—remember, a token doesn’t have to be justone character, it can be many charactersthat together comprise the token.
  • 87. Java I--Copyright © 2000 Tom HunterStringTokenizer Class: returnTokens• As the StringTokenizer class object moves itsway through a String, it automatically knows where itis in the String—you do not have to keep track ofthat.
  • 88. Java I--Copyright © 2000 Tom HunterStringTokenizer Class: Constructors• When you instantiate an object of typeStringTokenizer, you have threealternatives arguments for the Constructor1.) String stringtobetokenized2.) String stringtobetokenized,String delimiter3.) String stringtobetokenized,String delimiter,boolean returnTokensDefault delimiters:“ n, t, r ”DefaultreturnTokens= false.
  • 89. Java I--Copyright © 2000 Tom HunterStringTokenizer Class: Methods• The class has 6 methods:int countTokens()boolean hasMoreTokens()boolean hasMoreElements()Object nextElement()String nextToken()String nextToken( String delimiter )
  • 90. Java I--Copyright © 2000 Tom HunterStringTokenizer Class: countTokens()• This method counts how many more times this tokenizerobject’s nextToken can be counted.int countTokens()• It returns an integer with that number.
  • 91. Java I--Copyright © 2000 Tom HunterStringTokenizer Class: hasMoreTokens()• Simply, this tests if there are more tokens available fromthis tokenizer’s String.boolean hasMoreTokens()• If this method returns true, it anticipates that the a callto method nextToken() right after this would succeedin returning a token.—true if there are more tokens.
  • 92. Java I--Copyright © 2000 Tom HunterStringTokenizer Class: hasMoreElements()• This is used to override a method inherited from theEnumeration interface, which this class implements.boolean hasMoreElements()• In effect, this does the same thing as thehasMoreTokens() method.—true if there are more tokens.
  • 93. Java I--Copyright © 2000 Tom HunterStringTokenizer Class: nextToken()• This method is the workhorse. It gets the next tokenwaiting in the String that was used to instantiate thisobject.String nextToken()• If you neglected to precede this call with a successfulhasMoreTokens() method call, this method can throwa NoSuchElementException.
  • 94. Java I--Copyright © 2000 Tom HunterStringTokenizer Class: nextToken()• This method overloads nextToken(). It still returns thenext token in the String butString nextToken( String delimiter )• If you neglected to precede this call with a successfulhasMoreTokens() method call, this method can throwa NoSuchElementException.