Chapter 10 - Strings and Characters. 10.1Introduction In this chapter –Discuss class String, StringBuffer, and Character ( java.lang ) –Discuss class.

Slides:



Advertisements
Similar presentations
1 StringBuffer & StringTokenizer Classes Chapter 5 - Other String Classes.
Advertisements

Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Strings in Java 1. strings in java are handled by two classes String &
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
1 Working with String Duo Wei CS110A_ Empty Strings An empty string has no characters; its length is 0. Not to be confused with an uninitialized.
1 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Java Programming Strings Chapter 7.
Strings An extension of types A class that encompasses a character array and provides many useful behaviors Chapter 9 Strings are IMMUTABLE.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
Chapter 9 Characters and Strings. Topics Character primitives Character Wrapper class More String Methods String Comparison String Buffer String Tokenizer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
23-Jun-15 Strings, Etc. Part I: String s. 2 About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects,
Fundamental Programming Structures in Java: Strings.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 – Strings and Characters Outline 11.1 Introduction 11.2 Fundamentals of Characters and Strings.
Strings, Etc. Part I: Strings. About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects, have a defined.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
 Pearson Education, Inc. All rights reserved Strings, Characters and Regular Expressions.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 11 – Strings and Characters Outline 11.1 Introduction 11.2 Fundamentals of Characters and Strings.
Lesson 3 – Regular Expressions Sandeepa Harshanganie Kannangara MBCS | B.Sc. (special) in MIT.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 10 – Strings and Characters 10.1 Introduction 10.2 Fundamentals of Characters and Strings 10.3 String Constructors 10.4 String Methods length,
String Class. Objectives and Goals Identify 2 types of Strings: Literal & Symbolic. Learn about String constructors and commonly used methods Learn several.
The java.lang Package chapter 8 Java Certification Study Group February 2, 1998 Seth Ladd.
Chapter 7 Strings  Use the String class to process fixed strings.  Use the StringBuffer class to process flexible strings.  Use the StringTokenizer.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
An Introduction to Java Programming and Object-Oriented Application Development Chapter 7 Characters, Strings, and Formatting.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 10 – Strings and Characters Outline 10.1 Introduction 10.2 Fundamentals of Characters and Strings.
Java Overview. Comments in a Java Program Comments can be single line comments like C++ Example: //This is a Java Comment Comments can be spread over.
Chapter 7: Characters, Strings, and the StringBuilder.
1 Textual Data Many computer applications manipulate textual data word processors web browsers online dictionaries.
String Handling StringBuffer class character class StringTokenizer class.
Strings Chapter 7 CSCI CSCI 1302 – Strings2 Outline Introduction The String class –Constructing a String –Immutable and Canonical Strings –String.
Jaeki Song JAVA Lecture 07 String. Jaeki Song JAVA Outline String class String comparisons String conversions StringBuffer class StringTokenizer class.
Strings JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight.
Strings Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and.
String Definition A String is a set of characters that behaves as a single unit. The characters in a String include upper-case and lower-case letters,
Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Some people hear their own inner voices with great clearness, they live.
G51PR1 Introduction to Programming I University of Nottingham Unit 8 : Strings.
String Processing Word processing term papers, writing memoirs, sending messages, responding to surveys, placing online orders and registering products.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1.
1 Java Strings Dr. Randy M. Kaplan. 2 Strings – 1 Characters are a fundamental data type in Java It is common to assemble characters into units called.
Strings and Related Classes String and character processing Class java.lang.String Class java.lang.StringBuffer Class java.lang.Character Class java.util.StringTokenizer.
1 Lecture 12 Pointers and Strings Section 5.4, ,
String Definition A string is a set of characters that behaves as a single unit. The characters in a string include upper-case and lower- case letters,
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 – Strings and Characters Outline 11.1 Introduction 11.2 Fundamentals of Characters and Strings.
1 Lecture 8 Pointers and Strings: Part 2 Section 5.4, ,
1 Unit-2 Arrays, Strings and Collections. 2 Arrays - Introduction An array is a group of contiguous or related data items that share a common name. Used.
Chapter 10 – Strings and Characters
Strings, Characters and Regular Expressions
Strings, Characters and Regular Expressions
Strings, StringBuilder, and Character
Strings.
String and String Buffers
Primitive Types Vs. Reference Types, Strings, Enumerations
Modern Programming Tools And Techniques-I Lecture 11: String Handling
Chapter 7: Strings and Characters
Object Oriented Programming
MSIS 655 Advanced Business Applications Programming
Part a: Fundamentals & Class String
Exposure Java 2015 Pre-AP®CS Edition Chapter 12 Slides String Methods
Java – String Handling.
Lecture 07 String Jaeki Song.
OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS
Chapter 7 Strings Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. Use the String class to process fixed.
Object-Oriented Java Programming
In Java, strings are objects that belong to class java.lang.String .
Presentation transcript:

Chapter 10 - Strings and Characters

10.1Introduction 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

10.2Fundamentals 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

10.2Fundamentals 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 " " 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

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

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 StringBuffer s s7 = new String( myStringBuffer )

Class StringConstructors 1. main 1.1 Initialize arrays 1.2 Declarations 1.3 Constructors 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; s = new String( "hello" ); 18 buffer = 19 new StringBuffer( "Welcome to Java Programming!" ); // 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

2. Append output 3. GUI Program Output 30 output = "s1 = " + s "\ns2 = " + s "\ns3 = " + s "\ns4 = " + s "\ns5 = " + s "\ns6 = " + s "\ns7 = " + s7; JOptionPane.showMessageDialog( null, output, 39 "Demonstrating String Class Constructors", 40 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); 43 } 44}

10.4 String Methods length, charAt and getChars String methods –s1.length() Returns length of string Be careful, String s 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

Class StringMisc 1. main 1.1 Initialization 1.2 Output 2. s1.length() 3. Loop and print reversed characters 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. 9import javax.swing.*; 10 11public class StringMisc { 12 public static void main( String args[] ) 13 { 14 String s1, output; 15 char charArray[]; s1 = new String( "hello there" ); 18 charArray = new char[ 5 ]; // output the string 21 output = "s1: " + s1; // test the length method 24 output += "\nLength of s1: " + s1.length(); // loop through the characters in s1 and display reversed 27 output += "\nThe string reversed is: "; for ( int i = s1.length() - 1; i >= 0; i-- ) 30 output += s1.charAt( i ) + " ";

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

10.5Comparing String s Comparing String s –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"

10.5Comparing String s 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

10.5Comparing String s == 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

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

2. Tests for equality 3. compareTo 4. regionMatches // 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"; // 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"; // 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"; // 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

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

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

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

10.7Locating Characters and Substrings in String s 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

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

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

4. indexOf (two versions) 5. lastIndexOf (two versions) 6. GUI 30 output += "\nLast '$' is located at index " + 31 letters.lastIndexOf( '$' ); // test indexOf to locate a substring in a string 34 output += "\n\n\"def\" is located at index " + 35 letters.indexOf( "def" ); output += "\n\"def\" is located at index " + 38 letters.indexOf( "def", 7 ); output += "\n\"hello\" is located at index " + 41 letters.indexOf( "hello" ); // test lastIndexOf to find a substring in a string 44 output += "\n\nLast \"def\" is located at index " + 45 letters.lastIndexOf( "def" ); output += "\nLast \"def\" is located at index " + 48 letters.lastIndexOf( "def", 25 ); output += "\nLast \"hello\" is located at index " + 51 letters.lastIndexOf( "hello" ); JOptionPane.showMessageDialog( null, output, 54 "Demonstrating String Class \"index\" Methods", 55 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); 58 } 59} 60

Program Output

10.8Extracting Substrings from String s 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

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

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

Class StringConcat 1. main 1.1 Initialization 2. concat 3. GUI 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. 5import javax.swing.*; 6 7public class StringConcat { 8 public static void main( String args[] ) 9 { 10 String s1 = new String( "Happy " ), 11 s2 = new String( "Birthday" ), 12 output; output = "s1 = " + s "\ns2 = " + s2; output += "\n\nResult of s1.concat( s2 ) = " + 18 s1.concat( s2 ); output += "\ns1 after concatenation = " + s1; JOptionPane.showMessageDialog( null, output, 23 "Demonstrating String Method concat", 24 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); 27 } 28}

Program Output

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

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 String s with toString –s1.toCharArray() Creates a new character array containing copy of characters in s1

Class StringMisc2 1. main 1.1 Initialization 2. replace 3. toUpperCase and toLowerCase 4. trim 1// Fig. 10.9: StringMisc2.java 2// This program demonstrates the String methods replace, 3// toLowerCase, toUpperCase, trim, toString and toCharArray 4import javax.swing.*; 5 6public 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; output = "s1 = " + s "\ns2 = " + s "\ns3 = " + s3; // test method replace 19 output += "\n\nReplace 'l' with 'L' in s1: " + 20 s1.replace( 'l', 'L' ); // test toLowerCase and toUpperCase 23 output += 24 "\n\ns1.toUpperCase() = " + s1.toUpperCase() + 25 "\ns2.toLowerCase() = " + s2.toLowerCase(); // test trim method 28 output += "\n\ns3 after trim = \"" + s3.trim() + "\""; 29

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

Program Output

10.11 Using String Method valueOf static methods of class String –Take arguments and convert them to String s –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

Class StringValueOf 1. main 1.1 Initialization 2. valueOf 1// Fig : StringValueOf.java 2// This program demonstrates the String class valueOf methods. 3import javax.swing.*; 4 5public 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 = ; 13 float f = 2.5f; 14 double d = ; Object o = "hello"; // Assign to an Object reference 17 String output; 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

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

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

Class StringIntern 1. main 1.1 Initialization 2. Comparisons using == 2.1 Comparisons using equals 1// Fig : StringIntern.java 2// This program demonstrates the intern method 3// of the String class. 4import javax.swing.*; 5 6public class StringIntern { 7 public static void main( String args[] ) 8 { 9 String s1, s2, s3, s4, output; s1 = new String( "hello" ); 12 s2 = new String( "hello" ); // 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"; // 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

3. intern 4. Comparisons using == 29 // Use String intern method to get a unique copy of 30 // "hello" referred to by both s3 and s s3 = s1.intern(); 32 s4 = s2.intern(); // Test strings to determine if they are the same 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"; // 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"; // 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 Because s1 and s2 have the same contents, s3 and s4 are references to the same object in memory.

4. Comparisons using == 5. GUI Program Output 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"; JOptionPane.showMessageDialog( null, output, 69 "Demonstrating String Method intern", 70 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); 73 } 74} 75 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.

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

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

Class StringBuffer Constructors 1. main 1.1 Initialization (note use of constructors) 2. Output 3. GUI 1// Fig : StringBufferConstructors.java 2// This program demonstrates the StringBuffer constructors. 3import javax.swing.*; 4 5public 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" ); String output = 15 "buf1 = " + "\"" + buf1.toString() + "\"" + 16 "\nbuf2 = " + "\"" + buf2.toString() + "\"" + 17 "\nbuf3 = " + "\"" + buf3.toString() + "\""; JOptionPane.showMessageDialog( null, output, 20 "Demonstrating StringBuffer Class Constructors", 21 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); 24 } 25}

Program Output

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

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

Program Output

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

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

6. GUI Program Output 34 System.exit( 0 ); 35 } 36} 29 JOptionPane.showMessageDialog( null, output,30 "Demonstrating StringBuffer Character Methods", 31 JOptionPane.INFORMATION_MESSAGE ); 32 33

10.17 StringBuffer append Methods 10 overloaded append methods –Versions for each of the primitive data types, character arrays, String s, and Object s (using toString ) –StringBuffers and append used by compiler to concatenate String s String s = "BC" + 22; actually performed as new StringBuffer( "BC").append(22).toString(); StringBuffer created with String "BC" as contents Integer 22 appended to StringBuffer StringBuffer converted to a String ( toString ) Result assigned to s

Class StringBufferAppend 1. main 1.1 Initialization 2. append 1// Fig : StringBufferAppend.java 2// This program demonstrates the append 3// methods of the StringBuffer class. 4import javax.swing.*; 5 6public class StringBufferAppend { 7 public static void main( String args[] ) 8 { 9 Object o = "hello"; 10 String s = "good bye"; 11 char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; 12 boolean b = true; 13 char c = 'Z'; 14 int i = 7; 15 long l = ; 16 float f = 2.5f; 17 double d = ; 18 StringBuffer buf = new StringBuffer(); buf.append( o ); 21 buf.append( " " ); buf.append( s ); 24 buf.append( " " ); 25 buf.append( charArray ); 26 buf.append( " " ); 27 buf.append( charArray, 0, 3 ); 28 buf.append( " " ); 29 buf.append( b ); 30 buf.append( " " );

2. append 3. GUI Program Output 31 buf.append( c ); 32 buf.append( " " ); 33 buf.append( i ); 34 buf.append( " " ); 35 buf.append( l ); 36 buf.append( " " ); 37 buf.append( f ); 38 buf.append( " " ); 39 buf.append( d ); JOptionPane.showMessageDialog( null, 42 "buf = " + buf.toString(), 43 "Demonstrating StringBuffer append Methods", 44 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); 47 } 48}

10.18 StringBuffer Insertion and Deletion Methods Nine overloaded insert methods –Insert various data at any position in StringBuffer –insert( index, data ) Inserts data right before position index index must be greater than or equal to 0 delete methods –delete( start, end ) Deletes from start up to (not including) end –deleteCharAt( index ) Deletes character at index

Class StringBufferInsert 1. main 1.1 Initialization 2. insert 1// Fig : StringBufferInsert.java 2// This program demonstrates the insert and delete 3// methods of class StringBuffer. 4import javax.swing.*; 5 6public class StringBufferInsert { 7 public static void main( String args[] ) 8 { 9 Object o = "hello"; 10 String s = "good bye"; 11 char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; 12 boolean b = true; 13 char c = 'K'; 14 int i = 7; 15 long l = ; 16 float f = 2.5f; 17 double d = ; 18 StringBuffer buf = new StringBuffer(); buf.insert( 0, o ); 21 buf.insert( 0, " " ); 22 buf.insert( 0, s ); 23 buf.insert( 0, " " ); 24 buf.insert( 0, charArray ); 25 buf.insert( 0, " " ); 26 buf.insert( 0, b ); buf.insert( 0, " " ); 29 buf.insert( 0, c ); 30 buf.insert( 0, " " );

2. insert 3. deleteCharAt 4. delete 31 buf.insert( 0, i ); 32 buf.insert( 0, " " ); 33 buf.insert( 0, l ); 34 buf.insert( 0, " " ); 35 buf.insert( 0, f ); 36 buf.insert( 0, " " ); 37 buf.insert( 0, d ); String output = "buf after inserts:\n" + buf.toString(); buf.deleteCharAt( 10 ); // delete 5 in buf.delete( 2, 6 ); // delete.333 in output += "\n\nbuf after deletes:\n" + buf.toString(); JOptionPane.showMessageDialog( null, output, 47 "Demonstrating StringBufferer Inserts and Deletes", 48 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); 51 } 52}

Program Output

10.19 Character Class Examples Classes to treat primitive variables as objects –type wrappers: Boolean, Character, Double, Float, Byte, Short, Integer and Long All but Boolean and Character derive from Number Objects of these classes can be used anywhere an Object or Number is expected –In this section, study class Character (for information on all type-wrappers see java.lang package in API) Class Character

10.19 Character Class Examples Class Character static methods –Let c be a char –Character.isDefined( c ) Returns true if character defined in Unicode character set –Character.isJavaIdentifierStart ( c ) Returns true if character can be used as first letter of an identifier (letter, underscore ( _ ) or dollar sign ( $ ) ) –Character.isJavaIdentifierPart( c ) Returns true if character can be used in an identifier (letter, digit, underscore, or dollar sign) –Character.isDigit( c ) –Character.isLetter( c ) Character.isLetterOrDigit( c )

10.19 Character Class Examples Class Character static methods –Character.isLowerCase( c ) Character.toLowerCase( c ) –Returns converted character –Returns original if no change needed –Character.isUpperCase( c ) Character.toUpperCase( c ) –Character.digit( c, radix ) Converts character c into a digit of base radix –Character.forDigit( digit, radix ) Converts integer digit into a character using base radix

10.19 Character Class Examples Non- static methods of class Character –c1.charValue() Returns char value stored in Character object c1 –c1.toString() Returns String representation of c1 –c1.hashCode() Performs hashCode calculations Remember, used to store objects in hash tables for fast lookup –c1.equals( c2 ) Determines if c1 has same contents as c2

Class StaticCharMethods 1. main 1.1 Declarations 2. Constructor 2.1 GUI 1// Fig : StaticCharMethods.java 2// Demonstrates the static character testing methods 3// and case conversion methods of class Character 4// from the java.lang package. 5import javax.swing.*; 6import java.awt.*; 7import java.awt.event.*; 8 9public class StaticCharMethods extends JFrame { 10 private char c; 11 private JLabel prompt; 12 private JTextField input; 13 private JTextArea outputArea; public StaticCharMethods() 16 { 17 super( "Static Character Methods" ); Container container = getContentPane(); 20 container.setLayout( new FlowLayout() ); prompt = 23 new JLabel( "Enter a character and press Enter" ); 24 container.add( prompt ); input = new JTextField( 5 ); 27 input.addActionListener( 28 new ActionListener() { 29 public void actionPerformed( ActionEvent e )

2.2 Event handler 2.3 GUI 3. buildOutput 3.1 static method calls 32 c = s.charAt( 0 ); 34 } 35 } 36 ); 37 container.add( input ); outputArea = new JTextArea( 10, 20 ); 40 container.add( outputArea ); setSize( 300, 250 ); // set the window size 43 show(); // show the window 44 } public void buildOutput() 48 { 49 outputArea.setText( 50 "is defined: " + Character.isDefined( c ) + 51 "\nis digit: " + Character.isDigit( c ) + 52 "\nis Java letter: " + 53 Character.isJavaIdentifierStart( c ) + 54 "\nis Java letter or digit: " + 55 Character.isJavaIdentifierPart( c ) + 56 "\nis letter: " + Character.isLetter( c ) + 57 "\nis letter or digit: " + 58 Character.isLetterOrDigit( c ) + 59 "\nis lower case: " + Character.isLowerCase( c ) + 30 { 31 String s = e.getActionCommand(); 33 buildOutput();

3.1 static method calls 4. main } 67 StaticCharMethods application = new StaticCharMethods(); application.addWindowListener( 70 new WindowAdapter() { 71 public void windowClosing( WindowEvent e ) 72 { 73 System.exit( 0 ); 74 } 75 } 76 ); 77 } 60 "\nis upper case: " + Character.isUpperCase( c ) + 61 "\nto upper case: " + Character.toUpperCase( c ) + 62 "\nto lower case: " + Character.toLowerCase( c ) ); 65 public static void main( String args[] ) 66 {

Program Output

10.20 Class StringTokenizer Tokenization –Breaking statements into pieces –Class StringTokenizer breaks a String into component tokens Tokens separated by delimiters, typically whitespace characters Other characters may be used Class StringTokenizer –One constructor: StringTokenizer( myString ) Initialize StringTokenizer with a String Default delimiter " \n\t\r" (space, newline, tab, carriage return) Other constructors allow you to specify delimiter

10.20 Class StringTokenizer Methods –countTokens() Determines number of tokens in String –nextToken() Returns next token as a String –nextToken( delimiterString ) Changes delimiter while tokenizing a String –hasMoreTokens() Determines if there are more tokens to be tokenized

Class TokenTest 1. Constructor 1.1 GUI 1// Fig : TokenTest.java 2// Testing the StringTokenizer class of the java.util package 3import javax.swing.*; 4import java.util.*; 5import java.awt.*; 6import java.awt.event.*; 7 8public class TokenTest extends JFrame { 9 private JLabel prompt; 10 private JTextField input; 11 private JTextArea output; public TokenTest() 14 { 15 super( "Testing Class StringTokenizer" ); Container c = getContentPane(); 18 c.setLayout( new FlowLayout() ); prompt = 21 new JLabel( "Enter a sentence and press Enter" ); 22 c.add( prompt ); input = new JTextField( 20 ); 25 input.addActionListener( 26 new ActionListener() { 27 28

1.2 Event handler Tokenize String 1.3 GUI 2. main 29 public void actionPerformed( ActionEvent e ) 30 { 31 String stringToTokenize = e.getActionCommand(); 32 StringTokenizer tokens = 33 new StringTokenizer( stringToTokenize ); output.setText( "Number of elements: " + 36 tokens.countTokens() + 37 "\nThe tokens are:\n" ); while ( tokens.hasMoreTokens() ) 40 output.append( tokens.nextToken() + "\n" ); 41 } 42 } 43 ); 44 c.add( input ); output = new JTextArea( 10, 20 ); 47 output.setEditable( false ); 48 c.add( new JScrollPane( output ) ); setSize( 275, 260 ); // set the window size 51 show(); // show the window 52 } public static void main( String args[] ) 55 { 56 TokenTest app = new TokenTest(); app.addWindowListener( 59 new WindowAdapter() { 60 public void windowClosing( WindowEvent e ) Notice loop to tokenize the string

Program Output 61 { 62 System.exit( 0 ); 63 } 64 } 65 ); 66 } 67}

10.21 A Card Shuffling and Dealing Simulation Create card shuffling/dealing simulation –Create class Card with variables face and suit –Create deck, an array of Card s –To shuffle cards Loop through deck array Generate random number (0-51) and swap current card with that card –To deal cards, walk through deck array After all cards are dealt, ask user to shuffle again

Class DeckOfCards 1. Instance variables 1.1 Constructor 1.2 Initialize arrays 1.3 Create deck array 1.4 Initialize deck 1// Fig : DeckOfCards.java 2// Card shuffling and dealing program 3import javax.swing.*; 4import java.awt.*; 5import java.awt.event.*; 6 7public class DeckOfCards extends JFrame { 8 private Card deck[]; 9 private int currentCard; 10 private JButton dealButton, shuffleButton; 11 private JTextField displayCard; 12 private JLabel status; public DeckOfCards() 15 { 16 super( "Card Dealing Program" ); String faces[] = { "Ace", "Deuce", "Three", "Four", 19 "Five", "Six", "Seven", "Eight", 20 "Nine", "Ten", "Jack", "Queen", 21 "King" }; 22 String suits[] = { "Hearts", "Diamonds", 23 "Clubs", "Spades" }; deck = new Card[ 52 ]; 26 currentCard = -1; for ( int i = 0; i < deck.length; i++ ) 29 deck[ i ] = new Card( faces[ i % 13 ], 30 suits[ i / 13 ] );

2. GUI 2.1 Event handlers 3. GUI Container c = getContentPane(); 33 c.setLayout( new FlowLayout() ); dealButton = new JButton( "Deal card" ); 36 dealButton.addActionListener( 37 new ActionListener() { 38 public void actionPerformed( ActionEvent e ) 39 { 40 Card dealt = dealCard(); if ( dealt != null ) { 44 displayCard.setText( dealt.toString() ); 45 status.setText( "Card #: " + currentCard ); 46 } 47 else { 48 displayCard.setText( 49 "NO MORE CARDS TO DEAL" ); 50 status.setText( 51 "Shuffle cards to continue" ); 52 } 53 } 54 } 55 ); 56 c.add( dealButton ); shuffleButton = new JButton( "Shuffle cards" ); 59 shuffleButton.addActionListener( 60 new ActionListener() {

3.1 Event handler 4. GUI 5. shuffle 67 } 68 ); 69 c.add( shuffleButton ); displayCard = new JTextField( 20 ); 72 displayCard.setEditable( false ); 73 c.add( displayCard ); status = new JLabel(); 76 c.add( status ); setSize( 275, 120 ); // set the window size 79 show(); // show the window 80 } public void shuffle() 83 { 84 currentCard = -1; for ( int i = 0; i < deck.length; i++ ) { int j = ( int ) ( Math.random() * 52 ); 88 Card temp = deck[ i ]; // swap 89 deck[ i ] = deck[ j ]; // the 90 deck[ j ] = temp; // cards 66 } 61 public void actionPerformed( ActionEvent e ) 62 { 63 displayCard.setText( "SHUFFLING..." ); 64 shuffle(); 65 displayCard.setText( "DECK IS SHUFFLED" ); Swap current Card with random Card.

6. dealCard 7. main 91 } dealButton.setEnabled( true ); 94 } public Card dealCard() 98 { 99 if ( ++currentCard < deck.length ) 100 return deck[ currentCard ]; 101 else { 102 dealButton.setEnabled( false ); 103 return null; 104 } 105 } public static void main( String args[] ) 108 { 109 DeckOfCards app = new DeckOfCards(); app.addWindowListener( 112 new WindowAdapter() { 113 public void windowClosing( WindowEvent e ) 114 { 115 System.exit( 0 ); 116 } 117 } 118 ); 119 } 120}

Class Card Program Output class Card { 123 private String face; 124 private String suit; public Card( String f, String s ) 127 { 128 face = f; 129 suit = s; 130 } public String toString() { return face + " of " + suit; } 133}