Chapter 7 Strings Prerequisites for Part II hapter5 Arrays Chapter 6 Objects and Classes You can cover GUI after Chapter 8 Chapter 8 Inheritance and Polymorphism >Chapter 11 Getting Started with GUI Programming hapter 9 Abstract Classes and Interfaces Chapter 12 Event-Driven Programming ter 10 Object-Oriented Modeling Some people hear their own inner voices with great clearness, they live by what they hear... Chapter 15 Exceptions and Assertions You can cover Exceptions and vO after Chapter 8 hapter 16 Simple Input and Output Introduction to Java Programming, revised by Dai-kaiyu
Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 7 Strings Prerequisites for Part II Chapter 6 Objects and Classes Chapter 7 Strings Chapter 8 Inheritance and Polymorphism Chapter 5 Arrays Chapter 9 Abstract Classes and Interfaces Chapter 10 Object-Oriented Modeling Chapter 11 Getting Started with GUI Programming Chapter 12 Event-Driven Programming Chapter 15 Exceptions and Assertions Chapter 16 Simple Input and Output You can cover Exceptions and I/O after Chapter 8 You can cover GUI after Chapter 8 Some people hear their own inner voices with great clearness, they live by what they hear…
Objectives o To use the String class to process fixed strings(8.2) o To use the Character class to process a single character(87. 3) o To use the String Buffer class to process flexible strings($ 7.4) To use the String Tokenizer class to extract tokens from a string (§7.5) o To know the differences among the String, String Buffer, and String Tokenizer classes(8.2-7.5) o To use the JDK 1. 5 Scanner class for console input and scan tokens using words as delimiters(87.6) To input primitive values and strings from the keyboard using the Scanner class(§7.7) o To learn how to pass strings to the main method from the command line(§78) Introduction to Java Programming, revised by Dai-kaiyu
Liang,Introduction to Java Programming,revised by Dai-kaiyu 2 Objectives ⚫ To use the String class to process fixed strings (§7.2). ⚫ To use the Character class to process a single character (§7.3). ⚫ To use the StringBuffer class to process flexible strings (§7.4). ⚫ To use the StringTokenizer class to extract tokens from a string (§7.5). ⚫ To know the differences among the String, StringBuffer, and StringTokenizer classes (§7.2-7.5). ⚫ To use the JDK 1.5 Scanner class for console input and scan tokens using words as delimiters (§7.6). ⚫ To input primitive values and strings from the keyboard using the Scanner class (§7.7). ⚫ To learn how to pass strings to the main method from the command line (§7.8)
Introduction o String and character processing O Class java. lang String O Class java. lang String Buffer O Class java. lang Character O Class java util. String Tokenizer Introduction to Java Programming, revised by Dai-kaiyu
Liang,Introduction to Java Programming,revised by Dai-kaiyu 3 Introduction ⚫String and character processing Class java.lang.String Class java.lang.StringBuffer Class java.lang.Character Class java.util.StringTokenizer
Fundamentals of Characters and strings &3 ● Characters bUilding blocks of Java source programs ●Stng O Series of characters treated as single unit O May include letters, digits, etc OObject of class string Introduction to Java Programming, revised by Dai-kaiyu
Liang,Introduction to Java Programming,revised by Dai-kaiyu 4 Fundamentals of Characters and Strings ⚫Characters “Building blocks” of Java source programs ⚫String Series of characters treated as single unit May include letters, digits, etc. Object of class String
The String Class o Constructing a String o String message =Welcome to java O String message new String( "Welcome to Java) O String S= new String o Obtaining String length and Retrieving Individual Characters in a string String o String Concatenation(concat) Substrings(substring(index), substring(start, end)) o Comparisons(equals, compareTo) String Conversions Finding a Character or a Substring in a string Conversions between Strings and arrays Converting Characters and Numeric values to Strings Liang, Introduction to Java Programming, revised by Dai-kaiyu
Liang,Introduction to Java Programming,revised by Dai-kaiyu 5 The String Class ⚫ Constructing a String: String message = "Welcome to Java“; String message = new String("Welcome to Java“); String s = new String(); ⚫ Obtaining String length and Retrieving Individual Characters in a string String ⚫ String Concatenation (concat) ⚫ Substrings (substring(index), substring(start, end)) ⚫ Comparisons (equals, compareTo) ⚫ String Conversions ⚫ Finding a Character or a Substring in a String ⚫ Conversions between Strings and Arrays ⚫ Converting Characters and Numeric Values to Strings
String Constructs an empty string String(value: String) Constructs a string with the specified string literal value arD) Constructs a string with the specified character array harAt(index: int): char Returns the character at the specified index from this string compare To(anotherString: String ):int Compares this string with another string ompare Tolgnore Case(another: String): int Compares this string with another string ignoring cas onca( anotherString: String): String Concat this string with another string nds W ith(suffix: String): boolean Returns true if this string ends with the specified suffix uals(another String: String): boolean Returns true if this string is equal to anther string ualslgnore Case(anotherString:String):boolean Checks if this string equals anther string ignoring case Chars(int srcBegin, int src End, charl] dst, int Copies characters from this string into the destination character dst Begin): void array indexof(ch: int ) int Returns the index of the first occurrence of ch indexof(ch: int, fromIndex: int): int Returns the index of the first occurrence of ch after fromIndex indexOf(str: String): int Returns the index of the first occurrence of str ndexof(str: String, fromIndex: int): int urns the index of the first occurrence of str after fromIndex lastIndexof(ch: int ) int Returns the index of the last occurrence of ch astlndexof(ch: int, fromIndex: int): int Returns the index of the last occurrence of ch before fromIndex lastIndexof( str: String): int Retums the index of the last occurrence of str lastIndexOf(str: String, fromIndex: int) :int Returns the index of the last occurrence of str before fromlndex gionMatches( toffset:int,other: String, offset: Returns true if the specified subregion of this string exactly int, len: int): boolean matches the specified subregion of the string argument ength: int Returns the number of characters in this string place(oldChar: char,newChar: char): String Returns a new string with old Char replaced by newChar startsWith( prefix: String): boolean Returns true if this string starts with the specified prefix Returns the substring firom beginIndex ub String(beginIndex: int, endIndex: int): String Returns the substring from beginIndex to endIndex toChar Array): charl Returns a char array consisting characters from this string toLower Case(: String Returns a new string with all characters converted to lowercas tring(: String Returns a new string with itself pperCase(: String Returns a new string with all characters converted to uppercase 0: String Retums a string with blank characters trimmed on both sides copy ValueOf( data: charl): String Returns a new string consisting of the char array data yalueOfic: char): String Returns a string consisting of the character c Same as copy Value Ofidata: char): String valueOffd: double): String Returns a string representing the double value Returns a string representing the float value Returns a string representing the int value Returns a string representing the long value
Liang,Introduction to Java Programming,revised by Dai-kaiyu 6 String +String() +String(value: String) +String(value: char[]) +charAt(index: int): char +compareTo(anotherString: String): int +compareToIgnoreCase(anotherString: String): int +concat(anotherString: String): String +endsWith(suffix: String): boolean +equals(anotherString: String): boolean +equalsIgnoreCase(anotherString: String): boolean +getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): void +indexOf(ch: int): int +indexOf(ch: int, fromIndex: int): int +indexOf(str: String): int +indexOf(str: String, fromIndex: int): int +lastIndexOf(ch: int): int +lastIndexOf(ch: int, fromIndex: int): int +lastIndexOf(str: String): int +lastIndexOf(str: String, fromIndex: int): int +regionMatches(toffset: int, other: String, offset: int, len: int): boolean +length(): int +replace(oldChar: char, newChar: char): String +startsWith(prefix: String): boolean +subString(beginIndex: int): String +subString(beginIndex: int, endIndex: int): String +toCharArray(): char[] +toLowerCase(): String +toString(): String +toUpperCase(): String +trim(): String +copyValueOf(data: char[]): String +valueOf(c: char): String +valueOf(data: char[]): String +valueOf(d: double): String +valueOf(f: float): String +valueOf(i: int): String +valueOf(l: long): String Constructs an empty string Constructs a string with the specified string literal value Constructs a string with the specified character array Returns the character at the specified index from this string Compares this string with another string Compares this string with another string ignoring case Concat this string with another string Returns true if this string ends with the specified suffix Returns true if this string is equal to anther string Checks if this string equals anther string ignoring case Copies characters from this string into the destination character array Returns the index of the first occurrence of ch Returns the index of the first occurrence of ch after fromIndex Returns the index of the first occurrence of str Returns the index of the first occurrence of str after fromIndex Returns the index of the last occurrence of ch Returns the index of the last occurrence of ch before fromIndex Returns the index of the last occurrence of str Returns the index of the last occurrence of str before fromIndex Returns true if the specified subregion of this string exactly matches the specified subregion of the string argument Returns the number of characters in this string Returns a new string with oldChar replaced by newChar Returns true if this string starts with the specified prefix Returns the substring from beginIndex Returns the substring from beginIndex to endIndex Returns a char array consisting characters from this string Returns a new string with all characters converted to lowercase Returns a new string with itself Returns a new string with all characters converted to uppercase Returns a string with blank characters trimmed on both sides Returns a new string consisting of the char array data Returns a string consisting of the character c Same as copyValueOf(data: char[]): String Returns a string representing the double value Returns a string representing the float value Returns a string representing the int value Returns a string representing the long value
Constructing Strings String newString=new String(string literal) String message =new String("Welcome to Java") Since strings are used frequently, Java provides a shorthand initializer for creating a string. String message =Welcome to Java Introduction to Java Programming, revised by Dai-kaiyu
Liang,Introduction to Java Programming,revised by Dai-kaiyu 7 Constructing Strings String newString = new String(stringLiteral); String message = new String("Welcome to Java"); Since strings are used frequently, Java provides a shorthand initializer for creating a string: String message = "Welcome to Java";
1 //String Constructors. java 2 / /This program demonstrates the String class constructors 3 4 /Java extension packages 5 import javax. swing. "i 7 public class String Constructors i 9 / test String constructors 10 public static void main( String args) String default constructor 12 char charArrayl=(b,'i,r,'t,h,', Instantiates empty string 14 byte bytearrayl =i( byte)n, (byte)e Constructor copies String (byte)w, byte), byte)y (byte)e, byte)a, byte)'ri Constructor copies character array 18 String Buffer buffer 19 String s, sl, s2, s3, s4, s5, s6, s7, output; Constructor copies character- 21 s=new String("hello"); array subset 22 buffer new String Buffery Welcome to Java Programming! " 23 24 M/ use String constructors Constructor copies byte array 25 sl=new String: 2=new String(s ) Constructor copies bvte-array subset 27 s3= new String( charArray ) s4=new String( charArray, 6,3) s5=new String( byteArray, 4, 4 s6=new String( byteArray ) 31 s7=new String( buffer ) Constructor copies stringBuffer Liang, introduction to Java Trogrartinnng, reused Dy Dal-Kalyu
Liang,Introduction to Java Programming,revised by Dai-kaiyu Liang,Introduction to Java Programming,revised by Dai-kaiyu 8 1 // StringConstructors.java 2 // This program demonstrates the String class constructors. 3 4 // Java extension packages 5 import javax.swing.*; 6 7 public class StringConstructors { 8 9 // test String constructors 10 public static void main( String args[] ) 11 { 12 char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ', 13 'd', 'a', 'y' }; 14 byte byteArray[] = { ( byte ) 'n', ( byte ) 'e', 15 ( byte ) 'w', ( byte ) ' ', ( byte ) 'y', 16 ( byte ) 'e', ( byte ) 'a', ( byte ) 'r' }; 17 18 StringBuffer buffer; 19 String s, s1, s2, s3, s4, s5, s6, s7, output; 20 21 s = new String( "hello" ); 22 buffer = new StringBuffer( "Welcome to Java Programming!" ); 23 24 // use String constructors 25 s1 = new String(); 26 s2 = new String( s ); 27 s3 = new String( charArray ); 28 s4 = new String( charArray, 6, 3 ); 29 s5 = new String( byteArray, 4, 4 ); 30 s6 = new String( byteArray ); 31 s7 = new String( buffer ); 32 Constructor copies StringBuffer Constructor copies byte-array subset Constructor copies byte array Constructor copies characterarray subset Constructor copies character array Constructor copies String String default constructor instantiates empty string
33 /append Strings to output utput="sl="+sl+"Ⅶs2 2+"ns3="+s3+ "ins4="+s4+"ins5="+s5+"lns6="+s6+ 356739442 JOptionPane showMessage Dialog( null, output, Demons trating String Class Constructors", JOptionPane INFORMATION MESSAGE Systemexit(0 ) 453//end class String Cons tructors Demonstrating String Class Constructors S7=Welcome to Java programming Liang, Introduction to Java Programming, revised Liang, Introduction to Java pdgrakaimHg, revised by Dai-kaiyu
Liang,Introduction to Java Programming,revised by Dai-kaiyu Liang,Introduction to Java Programming,revised by Dai-kaiyu 9 33 // append Strings to output 34 output = "s1 = " + s1 + "\ns2 = " + s2 + "\ns3 = " + s3 + 35 "\ns4 = " + s4 + "\ns5 = " + s5 + "\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 45 } // end class StringConstructors
Strings Are Immutable A String object is immutable; its contents cannot be changed Does the following code change the contents of the string? String s=Java S=HTML After executing S: String er executing String string s=Javai s =HTML String object for"Java String object for"Java This string object is now unreferenced S¨ String Contents cannot be changed String object for"HTML Introduction to Java Programming, revised by Dai-kaiyu
Liang,Introduction to Java Programming,revised by Dai-kaiyu 10 Strings Are Immutable A String object is immutable; its contents cannot be changed. Does the following code change the contents of the string? String s = "Java"; s = "HTML"; s: String String object for "Java" s After executing String s = "Java"; After executing s = "HTML"; : String String object for "Java" s s: String Contents cannot be changed String object for "HTML" This string object is now unreferenced