1 / 77

Chapter 10 - Strings and Characters

Chapter 10 - Strings and Characters. 10.1 Introduction. In this chapter Discuss class String , StringBuffer , and Character ( java.lang ) Discuss class StringTokenizer ( java.util ) Techniques used here appropriate for making word processors, text editors, page layout software.

palma
Download Presentation

Chapter 10 - Strings and Characters

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 10 - Strings and Characters

  2. 10.1 Introduction • In this chapter • Discuss class String, StringBuffer, and Character (java.lang) • Discuss class StringTokenizer (java.util) • Techniques used here appropriate for making word processors, text editors, page layout software

  3. 10.2 Fundamentals of Characters and Strings • Characters • Character constant - integer represented as a character in single quotes (Unicode character set) • 'z' is integer value of z • Strings • Group of characters treated as a single unit • May include letters, digits, special characters (+,-*...) • Strings are objects of class String

  4. 10.2 Fundamentals of Characters and Strings • Strings (continued) • String literal (string constants or anonymous String objects) • Sequence of characters written in double quotes • "John Q. Doe" or "111222333" • Java treats all anonymous String objects with same contents as one object with many references • Assigning strings • May assign in declaration String color = "blue"; • color is a String reference

  5. 10.3 String Constructors • Constructors for class String • s1 = new String() • s1 is an empty string • s2 = new String( anotherString ) • s2 is a copy of anotherString • s3 = new String( charArray ) • s3 contains all the characters in charArray • s4 = new String( charArray, offset, numElements ) • s4 contains numElements characters from charArray, starting at location offset • s5 = new String( byteArray, offset, numElements) • As above, but with a byteArray

  6. 10.3 String Constructors • Constructors for class String • s6 = new String( byteArray ) • s6 contains copy of entire byteArray • StringBuffer • Dynamically resizable, modifiable string (more later) • StringBuffer buffer = new StringBuffer( "Hello there" ); • Can initialize Strings with StringBuffers s7 = new String( myStringBuffer )

  7. 1// Fig. 10.1: StringConstructors.java 2// This program demonstrates the String class constructors. 3import javax.swing.*; 4 5public class StringConstructors { 6 public static void main( String args[] ) 7 { 8 char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ', 9 'd', 'a', 'y' }; 10 byte byteArray[] = { (byte) 'n', (byte) 'e', (byte) 'w', 11 (byte) ' ', (byte) 'y', (byte) 'e', 12 (byte) 'a', (byte) 'r' }; 13 StringBuffer buffer; 14 String s, s1, s2, s3, s4, s5, s6, s7, output; 15 16 17 s = new String( "hello" ); 18 buffer = 19 new StringBuffer( "Welcome to Java Programming!" ); 20 21 // use the String constructors 22 s1 = new String(); 23 s2 = new String( s ); 24 s3 = new String( charArray ); 25 s4 = new String( charArray, 6, 3 ); 26 s5 = new String( byteArray, 4, 4 ); 27 s6 = new String( byteArray ); 28 s7 = new String( buffer ); 29 Class StringConstructors 1. main 1.1 Initialize arrays 1.2 Declarations 1.3 Constructors

  8. 34 "\ns5 = " + s5 + 35 "\ns6 = " + s6 + 36 "\ns7 = " + s7; 37 38 JOptionPane.showMessageDialog( null, output, 39 "Demonstrating String Class Constructors", 40 JOptionPane.INFORMATION_MESSAGE ); 41 42 System.exit( 0 ); 43 } 44 } 30 output = "s1 = " + s1 + 31 "\ns2 = " + s2 + 32 "\ns3 = " + s3 + 33 "\ns4 = " + s4 + 2. Append output 3. GUI Program Output

  9. 10.4 String Methods length, charAt and getChars • String methods • s1.length() • Returns length of string • Be careful, Strings do not have an instance variable length like arrays • s1.length is an error • s1.charAt( index ) • Returns char at location index • Numbered like arrays (start at position 0) • s1.getChars( start, end, charArray, offset ) • Copies characters in s1 from index start to index end to location offset in charArray

  10. 1 // Fig. 10.2: StringMisc.java 2 // This program demonstrates the length, charAt and getChars 3 // methods of the String class. 4 // 5 // Note: Method getChars requires a starting point 6 // and ending point in the String. The starting point is the 7 // actual subscript from which copying starts. The ending point 8 // is one past the subscript at which the copying ends. 9 import javax.swing.*; 10 11 public class StringMisc { 12 public static void main( String args[] ) 13 { 14 String s1, output; 15 char charArray[]; 16 17 s1 = new String( "hello there" ); 18 charArray = new char[ 5 ]; 19 20 // output the string 21 output = "s1: " + s1; 22 23 // test the length method 24 output += "\nLength of s1: " + s1.length(); 25 26 // loop through the characters in s1 and display reversed 27 output += "\nThe string reversed is: "; 28 29 for ( int i = s1.length() - 1; i >= 0; i-- ) 30 output += s1.charAt( i ) + " "; Class StringMisc 1. main 1.1 Initialization 1.2 Output 2. s1.length() 3. Loop and print reversed characters

  11. 34 s1.getChars( 0, 5, charArray, 0 ); 35 output += "\nThe character array is: "; 36 37 for ( int i = 0; i < charArray.length; i++ ) 38 output += charArray[ i ]; 39 40 JOptionPane.showMessageDialog( null, output, 41 "Demonstrating String Class Constructors", 42 JOptionPane.INFORMATION_MESSAGE ); 43 44 System.exit( 0 ); 45 } 46 } 33 // copy characters from string into char array 4. getChars 5. GUI Program Output

  12. 10.5 Comparing Strings • Comparing Strings • All characters represented as numeric codes (Appendix D) • When computer compares strings, compares numeric codes • Lexicographical comparison - compare Unicode values • Lowercase different than uppercase • Comparison methods • s1.equals( "Hi" ) • Returns true if s1 equal to "Hi" • Capitalization (case) matters • s1.equalsIgnoreCase( otherString ) • Tests for equality, case does not matter • "hello" equal to "HELLO"

  13. 10.5 Comparing Strings • Comparison methods • s1.compareTo( otherString ) • Uses lexicographical comparison • Returns 0 if strings equal • Returns negative number if s1 < otherString • Returns positive number if s1 > otherString • s1.regionMatches( offset, otherString, start, end ) • Compares s1 from location offset to otherString from location start to end • s1.regionMatches( ignoreCase, offset, otherString, start, end ) • As above, but if ignoreCase is true, case is ignored

  14. 10.5 Comparing Strings • == operator • When used with primitive data types, returns true if equal • When used with references, returns true if point to same location in memory • Remember, Java treats all anonymous String objects with same contents as one object with many references s1 = "hello"; //uses anonymous object s2 = new String( "hello" ); s1 == "hello"; //true s2 == "hello"; //false

  15. 29 else 1 // Fig. 10.3: StringCompare 30 output += "s1 does not equal \"hello\"\n"; 2 // This program demonstrates the methods equals, 3 // equalsIgnoreCase, compareTo, and regionMatches 4 // of the String class. 5 import javax.swing.JOptionPane; 6 7 public class StringCompare { 8 public static void main( String args[] ) s1 will fail this test because it was not initialized with an anonymous String object. 9 { 10 String s1, s2, s3, s4, output; 11 12 s1 = new String( "hello" ); 13 s2 = new String( "good bye" ); 14 s3 = new String( "Happy Birthday" ); 15 s4 = new String( "happy birthday" ); 16 17 output = "s1 = " + s1 + "\ns2 = " + s2 + 18 "\ns3 = " + s3 + "\ns4 = " + s4 + "\n\n"; 19 20 // test for equality 21 if ( s1.equals( "hello" ) ) 22 output += "s1 equals \"hello\"\n"; 23 else 24 output += "s1 does not equal \"hello\"\n"; 25 26 // test for equality with == 27 if ( s1 == "hello" ) 28 output += "s1 equals \"hello\"\n"; Class StringCompare 1. main 1.1 Initialization 1.2 Append output 2. Tests for equality

  16. 31 32 // test for equality--ignore case 33 if ( s3.equalsIgnoreCase( s4 ) ) 34 output += "s3 equals s4\n"; 35 else 36 output += "s3 does not equal s4\n"; 37 38 // test compareTo 39 output += 40 "\ns1.compareTo( s2 ) is " + s1.compareTo( s2 ) + 41 "\ns2.compareTo( s1 ) is " + s2.compareTo( s1 ) + 42 "\ns1.compareTo( s1 ) is " + s1.compareTo( s1 ) + 43 "\ns3.compareTo( s4 ) is " + s3.compareTo( s4 ) + 44 "\ns4.compareTo( s3 ) is " + s4.compareTo( s3 ) + 45 "\n\n"; 46 47 // test regionMatches (case sensitive) 48 if ( s3.regionMatches( 0, s4, 0, 5 ) ) 49 output += "First 5 characters of s3 and s4 match\n"; 50 else 51 output += 52 "First 5 characters of s3 and s4 do not match\n"; 53 54 // test regionMatches (ignore case) 55 if ( s3.regionMatches( true, 0, s4, 0, 5 ) ) 56 output += "First 5 characters of s3 and s4 match"; 57 else 58 output += 59 "First 5 characters of s3 and s4 do not match"; 60 2. Tests for equality 3. compareTo 4. regionMatches

  17. 62 "Demonstrating String Class Constructors", 63 JOptionPane.INFORMATION_MESSAGE ); 64 65 System.exit( 0 ); 66 } 67 } Using equals, ==, and equalsIgnoreCase 61 JOptionPane.showMessageDialog( null, output, 5. GUI Program Output

  18. 10.6 String Method hashCode • Hash table • Fast access to data • Stores information using a calculation that makes a hash code • Code used to choose location to store object in table • To retrieve information, use same calculation • Hash code determined, go to that location of table • Get original value • Every object can be stored in a hash table • Class Object defines method hashCode • Inherited by all subclasses • hashCode overridden in class String to provide a good hash code distribution

  19. 1 // Fig. 10.5: StringHashCode.java1 2 // This program demonstrates the method 3 // hashCode of the String class. 4 import javax.swing.*; 5 6 public class StringHashCode { 7 public static void main( String args[] ) 8 { 9 String s1 = "hello", 10 s2 = "Hello"; 11 12 String output = 13 "The hash code for \"" + s1 + "\" is " + 14 s1.hashCode() + 15 "\nThe hash code for \"" + s2 + "\" is " + 16 s2.hashCode(); 17 18 JOptionPane.showMessageDialog( null, output, 19 "Demonstrating String Method hashCode", 20 JOptionPane.INFORMATION_MESSAGE ); 21 22 System.exit( 0 ); 23 } 24 } Class StringHashCode 1. main 1.1 Initialization 2. hashCode 3. GUI Program Output

  20. 10.7 Locating Characters and Substrings in Strings • Search methods • s1.indexOf( integerRep ) • integerRep - integer representation of a character ('z') • Returns index of the first occurrence of the character in the string • Returns -1 if not found • s1.indexOf( integerRep, startSearch ) • As above, but begins search at position startSearch • s1.lastIndexOf( integerRep ) • Returns index of last occurrence of character in string • s1.lastIndexOf( integerRep, startSearch ) • As above, but searches backwards from position startSearch

  21. 10.7 Locating Characters and Substrings in Strings • Search methods (continued) • Can use indexOf and lastIndexOf with Strings • Search for substrings within a string • Identical usage as with characters, i.e. s1.indexOf( "hi" ) s1.lastIndexOf( "this", 24 )

  22. 1 // Fig. 10.6: StringIndexMethods.java 2 // This program demonstrates the String 3 // class index methods. 4 import javax.swing.*; 5 6 7 public class StringIndexMethods { 8 public static void main( String args[] ) 9 { 10 String letters = "abcdefghijklmabcdefghijklm"; 11 String output; 12 13 // test indexOf to locate a character in a string 14 output = "'c' is located at index " + 15 letters.indexOf( 'c' ); 16 17 output += "\n'a' is located at index " + 18 letters.indexOf( 'a', 1 ); 19 20 output += "\n'$' is located at index " + 21 letters.indexOf( '$' ); 22 23 // test lastIndexOf to find a character in a string 24 output += "\n\nLast 'c' is located at index " + 25 letters.lastIndexOf( 'c' ); 26 27 output += "\nLast 'a' is located at index " + 28 letters.lastIndexOf( 'a', 25 ); 29 Class StringIndexMethods 1. main 1.1 Initialization 2. indexOf (two versions) 3. lastIndexOf (two versions)

  23. 34 output += "\n\n\"def\" is located at index " + 35 letters.indexOf( "def" ); 36 37 output += "\n\"def\" is located at index " + 38 letters.indexOf( "def", 7 ); 39 40 output += "\n\"hello\" is located at index " + 41 letters.indexOf( "hello" ); 42 43 // test lastIndexOf to find a substring in a string 44 output += "\n\nLast \"def\" is located at index " + 45 letters.lastIndexOf( "def" ); 46 47 output += "\nLast \"def\" is located at index " + 48 letters.lastIndexOf( "def", 25 ); 49 50 output += "\nLast \"hello\" is located at index " + 51 letters.lastIndexOf( "hello" ); 52 53 JOptionPane.showMessageDialog( null, output, 54 "Demonstrating String Class \"index\" Methods", 55 JOptionPane.INFORMATION_MESSAGE ); 56 57 System.exit( 0 ); 58 } 59 } 60 30 output += "\nLast '$' is located at index " + 31 letters.lastIndexOf( '$' ); 32 33 // test indexOf to locate a substring in a string 4. indexOf (two versions) 5. lastIndexOf (two versions) 6. GUI

  24. Program Output

  25. 10.8 Extracting Substrings from Strings • substring methods • Return a String object • s1.substring( startIndex ) • Returns a substring from startIndex to the end of the string • s1.substring( start, end ) • Returns a substring from location start up to, but not including, location end • If index out of bounds, StringIndexOutOfBoundsException generated

  26. 1 // Fig. 10.7: SubString.java 2 // This program demonstrates the 3 // String class substring methods. 4 import javax.swing.*; 5 6 public class SubString { 7 public static void main( String args[] ) 8 { 9 String letters = "abcdefghijklmabcdefghijklm"; 10 String output; 11 12 // test substring methods 13 output = "Substring from index 20 to end is " + 14 "\"" + letters.substring( 20 ) + "\"\n"; 15 16 output += "Substring from index 0 up to 6 is " + 17 "\"" + letters.substring( 0, 6 ) + "\""; 18 19 JOptionPane.showMessageDialog( null, output, 20 "Demonstrating String Class Substring Methods", 21 JOptionPane.INFORMATION_MESSAGE ); 22 23 System.exit( 0 ); 24 } 25 } Class Substring 1. main 1.1 Initialization 2. substring methods 3. GUI Program Output

  27. 10.9 Concatenating Strings • Method concat • Concatenates two Strings, returns new String object • Original Strings are not modified • s1.concat( s2 ) • Returns concatenation of s1 and s2 • If no argument, returns s1

  28. 1 // Fig. 10.8: StringConcat.java 2 // This program demonstrates the String class concat method. 3 // Note that the concat method returns a new String object. It 4 // does not modify the object that invoked the concat method. 5 import javax.swing.*; 6 7 public class StringConcat { 8 public static void main( String args[] ) 9 { 10 String s1 = new String( "Happy " ), 11 s2 = new String( "Birthday" ), 12 output; 13 14 output = "s1 = " + s1 + 15 "\ns2 = " + s2; 16 17 output += "\n\nResult of s1.concat( s2 ) = " + 18 s1.concat( s2 ); 19 20 output += "\ns1 after concatenation = " + s1; 21 22 JOptionPane.showMessageDialog( null, output, 23 "Demonstrating String Method concat", 24 JOptionPane.INFORMATION_MESSAGE ); 25 26 System.exit( 0 ); 27 } 28 } Class StringConcat 1. main 1.1 Initialization 2. concat 3. GUI

  29. Program Output

  30. 10.10 Miscellaneous String Methods • Miscellaneous methods • s1.replace( char1, char2 ) • Returns a new String, replacing all instances of char1 with char2 • Use integer representations: 'z', '1', etc. • Original String not changed • If no instances of char1, original string returned • s1.toUpperCase() • Returns new String object with all letters capitalized • If no changes needed, original string returned • Original string unchanged • s1.toLowerCase() similar

  31. 10.10 Miscellaneous String Methods • Miscellaneous methods (continued) • s1.trim() • Returns new String, removing all whitespace characters at beginning or end • Original unchanged • s1.toString() • All objects can be converted to Strings with toString • s1.toCharArray() • Creates a new character array containing copy of characters in s1

  32. 1 // Fig. 10.9: StringMisc2.java 2 // This program demonstrates the String methods replace, 3 // toLowerCase, toUpperCase, trim, toString and toCharArray 4 import javax.swing.*; 5 6 public class StringMisc2 { 7 public static void main( String args[] ) 8 { 9 String s1 = new String( "hello" ), 10 s2 = new String( "GOOD BYE" ), 11 s3 = new String( " spaces " ), 12 output; 13 14 output = "s1 = " + s1 + 15 "\ns2 = " + s2 + 16 "\ns3 = " + s3; 17 18 // test method replace 19 output += "\n\nReplace 'l' with 'L' in s1: " + 20 s1.replace( 'l', 'L' ); 21 22 // test toLowerCase and toUpperCase 23 output += 24 "\n\ns1.toUpperCase() = " + s1.toUpperCase() + 25 "\ns2.toLowerCase() = " + s2.toLowerCase(); 26 27 // test trim method 28 output += "\n\ns3 after trim = \"" + s3.trim() + "\""; 29 Class StringMisc2 1. main 1.1 Initialization 2. replace 3. toUpperCase and toLowerCase 4. trim

  33. 34 char charArray[] = s1.toCharArray(); 35 36 output += "\n\ns1 as a character array = "; 37 38 for ( int i = 0; i < charArray.length; ++i ) 39 output += charArray[ i ]; 40 41 JOptionPane.showMessageDialog( null, output, 42 "Demonstrating Miscellaneous String Methods", 43 JOptionPane.INFORMATION_MESSAGE ); 44 45 System.exit( 0 ); 47 } 46 } 30 // test toString method 31 output += "\n\ns1 = " + s1.toString(); 32 33 // test toCharArray method 5. toString 6. toCharArray 7. GUI

  34. Program Output

  35. 10.11 Using String Method valueOf • static methods of class String • Take arguments and convert them to Strings • String.valueOf( charArray ) • Returns new String object containing characters in charArray • String.valueOf( charArray, startIndex, numChars ) • As above, but starts from position startIndex and copies numChars characters • Other versions of valueOf take boolean, char, int, long, float, double, and Object • Objects converted to Strings with toString

  36. 1 // Fig. 10.10: StringValueOf.java 2 // This program demonstrates the String class valueOf methods. 3 import javax.swing.*; 4 5 public class StringValueOf { 6 public static void main( String args[] ) 7 { 8 char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; 9 boolean b = true; 10 char c = 'Z'; 11 int i = 7; 12 long l = 10000000; 13 float f = 2.5f; 14 double d = 33.333; 15 16 Object o = "hello"; // Assign to an Object reference 17 String output; 18 19 output = "char array = " + String.valueOf( charArray ) + 20 "\npart of char array = " + 21 String.valueOf( charArray, 3, 3 ) + 22 "\nboolean = " + String.valueOf( b ) + 23 "\nchar = " + String.valueOf( c ) + 24 "\nint = " + String.valueOf( i ) + 25 "\nlong = " + String.valueOf( l ) + 26 "\nfloat = " + String.valueOf( f ) + 27 "\ndouble = " + String.valueOf( d ) + 28 "\nObject = " + String.valueOf( o ); 29 Class StringValueOf 1. main 1.1 Initialization 2. valueOf

  37. 33 34 System.exit( 0 ); 35 } 36 } 30 JOptionPane.showMessageDialog( null, output, 31 "Demonstrating String Class valueOf Methods", 32 JOptionPane.INFORMATION_MESSAGE ); 3. GUI Program Output

  38. 10.12 String Method intern • Method intern • Improves string comparison performance • Returns reference guaranteed to have same contents • Multiple interns generate references to same object • Strings can be compared with == (same location in memory) instead of equals • Much faster than comparing character by character

  39. 1 // Fig. 10.11: StringIntern.java 2 // This program demonstrates the intern method 3 // of the String class. 4 import javax.swing.*; 5 6 public class StringIntern { 7 public static void main( String args[] ) 8 { 9 String s1, s2, s3, s4, output; 10 11 s1 = new String( "hello" ); 12 s2 = new String( "hello" ); 13 14 // Test strings to determine if they are the same 15 // String object in memory. 16 if ( s1 == s2 ) 17 output = 18 "s1 and s2 are the same object in memory"; 19 else 20 output = 21 "s1 and s2 are not the same object in memory"; 22 23 // Test strings for equality of contents 24 if ( s1.equals( s2 ) ) 25 output += "\ns1 and s2 are equal"; 26 else 27 output += "\ns1 and s2 are not equal"; 28 Class StringIntern 1. main 1.1 Initialization 2. Comparisons using == 2.1 Comparisons using equals

  40. 34 35 // Test strings to determine if they are the same Because s1 and s2 have the same contents, s3 and s4 are references to the same object in memory. 36 // String object in memory. 37 if ( s3 == s4 ) 38 output += 39 "\ns3 and s4 are the same object in memory"; 40 else 41 output += 42 "\ns3 and s4 are not the same object in memory"; 43 44 // Determine if s1 and s3 refer to the same object 45 if ( s1 == s3 ) 46 output += 47 "\ns1 and s3 are the same object in memory"; 48 else 49 output += 50 "\ns1 and s3 are not the same object in memory"; 51 52 // Determine if s2 and s4 refer to the same object 53 if ( s2 == s4 ) 54 output += 55 "\ns2 and s4 are the same object in memory"; 56 else 57 output += 58 "\ns2 and s4 are not the same object in memory"; 59 29 // Use String intern method to get a unique copy of 30 // "hello" referred to by both s3 and s4. 31 s3 = s1.intern(); 32 s4 = s2.intern(); 33 3. intern 4. Comparisons using ==

  41. 67 68 JOptionPane.showMessageDialog( null, output, 69 "Demonstrating String Method intern", 70 JOptionPane.INFORMATION_MESSAGE ); 71 s1 and s2 both contain "hello" but are not the same object. s3 and s4 were interned from s1 and s2, and are the same object in memory. 72 System.exit( 0 ); 73 } 74 } 75 60 // Determine if s1 and s4 refer to the same object 61 if ( s1 == s4 ) 62 output += 63 "\ns1 and s4 are the same object in memory"; 64 else 65 output += 66 "\ns1 and s4 are not the same object in memory"; 4. Comparisons using == 5. GUI Program Output

  42. 10.13 StringBuffer Class • Class String • Once a String is created, it cannot be changed • Class StringBuffer • Can create modifiable Strings • Capable of storing number of characters specified by capacity • If capacity exceeded, automatically expands to hold new characters • Can use + and += operators

  43. 10.14 StringBuffer Constructors • StringBuffer constructors • buf1 = new StringBuffer(); • Creates empty StringBuffer, capacity of 16 characters • buf2 = new StringBuffer( capacity ); • Creates empty StringBuffer with specified capacity • but3 = new StringBuffer( myString ); • Creates a StringBuffer containing myString, with capacity myString.length() + 16

  44. 1 // Fig. 10.12: StringBufferConstructors.java 2 // This program demonstrates the StringBuffer constructors. 3 import javax.swing.*; 4 5 public class StringBufferConstructors { 6 public static void main( String args[] ) 7 { 8 StringBuffer buf1, buf2, buf3; 9 10 buf1 = new StringBuffer(); 11 buf2 = new StringBuffer( 10 ); 12 buf3 = new StringBuffer( "hello" ); 13 14 String output = 15 "buf1 = " + "\"" + buf1.toString() + "\"" + 16 "\nbuf2 = " + "\"" + buf2.toString() + "\"" + 17 "\nbuf3 = " + "\"" + buf3.toString() + "\""; 18 19 JOptionPane.showMessageDialog( null, output, 20 "Demonstrating StringBuffer Class Constructors", 21 JOptionPane.INFORMATION_MESSAGE ); 22 23 System.exit( 0 ); 24 } 25 } Class StringBuffer Constructors 1. main 1.1 Initialization (note use of constructors) 2. Output 3. GUI

  45. Program Output

  46. 10.15 StringBuffer Methods length, capacity, setLength and ensureCapacity • StringBuffer methods • length - returns length • capacity - returns capacity • setLength( newLength ) • Changes length of StringBuffer to newLength • If too long, truncates excess characters • If too short, fills with null character (numeric representation of 0) • ensureCapacity( size ) • Expands capacity to a minimum of size • If size less than current capacity, then capacity is unchanged

  47. 1 // Fig. 10.13: StringBufferCapLen.java 2 // This program demonstrates the length and 3 // capacity methods of the StringBuffer class. 4 import javax.swing.*; 5 6 public class StringBufferCapLen { 7 public static void main( String args[] ) 8 { 9 StringBuffer buf = 10 new StringBuffer( "Hello, how are you?" ); 11 12 String output = "buf = " + buf.toString() + 13 "\nlength = " + buf.length() + 14 "\ncapacity = " + buf.capacity(); 15 16 buf.ensureCapacity( 75 ); 17 output += "\n\nNew capacity = " + buf.capacity(); 18 19 buf.setLength( 10 ); 20 output += "\n\nNew length = " + buf.length() + 21 "\nbuf = " + buf.toString(); 22 23 JOptionPane.showMessageDialog( null, output, 24 "StringBuffer length and capacity Methods", 25 JOptionPane.INFORMATION_MESSAGE ); 26 27 28 System.exit( 0 ); 29 } 30 } Class StringBufferCapLen 1. main 1.1 Initialization 2. length 2.1 capacity 3. ensureCapacity 3.1 setLength 4. GUI

  48. Program Output

  49. 10.16 StringBuffer Methods charAt, setCharAt, getChars and reverse • StringBuffer methods • charAt( index ) - returns character at position index • setCharAt( index, char ) • Sets character at position index to char • getChars( start, end, charArray, loc ) • Copies from position start up to (not including) end into location loc in charArray • reverse - reverses contents of StringBuffer

  50. 1 // Fig. 10.14: StringBufferChars.java 2 // The charAt, setCharAt, getChars, and reverse methods 3 // of class StringBuffer. 4 import javax.swing.*; 5 6 public class StringBufferChars { 7 public static void main( String args[] ) 8 { 9 StringBuffer buf = new StringBuffer( "hello there" ); 10 11 String output = "buf = " + buf.toString() + 12 "\nCharacter at 0: " + buf.charAt( 0 ) + 13 "\nCharacter at 4: " + buf.charAt( 4 ); 14 15 char charArray[] = new char[ buf.length() ]; 16 buf.getChars( 0, buf.length(), charArray, 0 ); 17 output += "\n\nThe characters are: "; 18 19 for ( int i = 0; i < charArray.length; ++i ) 20 output += charArray[ i ]; 21 22 buf.setCharAt( 0, 'H' ); 23 buf.setCharAt( 6, 'T' ); 24 output += "\n\nbuf = " + buf.toString(); 25 26 buf.reverse(); 27 output += "\n\nbuf = " + buf.toString(); 28 Class StringBufferChars 1. main 1.1 Initialization 2. charAt 3. getChars 4. setCharAt 5. reverse

More Related