The String Class PDF - AP Computer Science A
Document Details
Uploaded by JovialInfinity7753
Tags
Summary
These are lecture notes about the String class in Java, focusing on its properties, methods, and usage in AP Computer Science A.
Full Transcript
The String Class AP Computer Science A 1 Objectives: Learn about literal strings Learn about String constructors and commonly used methods Understand immutability of strings Learn to format numbers into strings and extract numbers from strings...
The String Class AP Computer Science A 1 Objectives: Learn about literal strings Learn about String constructors and commonly used methods Understand immutability of strings Learn to format numbers into strings and extract numbers from strings 2 The String class An object of the String class represents a string of characters. The String class belongs to the java.lang package, which is built into Java. Like other classes, String has constructors and methods. Unlike other classes, String has two operators, + and += (used for concatenation). 3 Literal Strings Literal strings are anonymous constant objects of the String class that are defined as text in double quotes. Literal strings don’t have to be constructed: they are “just there.” Use the String Constructor: String msg1 = new String (“That’s right!”); Or don’t use the constructor: String msg2 = “That’s Right!”; char T h a t ‘ s R i g h t ! index: 0 1 2 3 4 5 6 7 8 9 10 11 12 4 Literal Strings (cont’d) can be assigned to String variables. can be passed to methods and constructors as parameters. have methods you can call: String fileName = "fish.dat"; if ("Start".equals(cmd))... 5 Literal Strings (cont’d) The string text may include “escape” characters. For example: ⮚ \\ stands for \ ⮚ \” stands for “ ⮚ \n stands for the newline character ⮚ Java treats escape sequence as one character String s1 = "Biology”; String s2 = "C:\\jdk1.4\\docs"; String s3 = "Hello\n"; 6 Immutability Once created, a string cannot be changed: none of its methods changes the string. Such objects are called immutable. Immutable objects are convenient because several references can point to the same object safely: there is no danger of changing an object through one reference without the others being aware of the change. 7 Immutability When you change a String, it creates a new String saved in a different memory location! 10-8 Immutability (cont’d) Advantage: more efficient, no need to copy in order preserve the original string. String s1 = "Sun"; String s1 = "Sun"; String s2 = s1; String s2 = new String(s1); s1 s1 "Sun" "Sun" s2 s2 "Sun" OK Less efficient: wastes memory 9 Immutability (cont’d) Disadvantage: less efficient — you need to create a new string and throw away the old one for every small change. String s = "sun"; char ch = Character.toUpperCase(s.charAt (0)); s = ch + s.substring (1); s "sun" "Sun" 10 Difference in construction Initializing a using the String class constructor always creates a new String in a new location, no matter what it contains Initializing a String literal with “ “ will only create a String in a new location if it’s contents are different than other Strings in memory String str1= new String(“test”); str1.equals(str2) //true String str2= new String(“test”); str1==str2 //false; different locations str3.equals(str1) //true String str3=”test”; str3==str4 //true String str4=”test”; 10-11 String parameters Strings are objects that holds a reference to their location in memory! BUT: remember that Strings are immutable- when their content is modified the String is saved to a new location public static void main(String[] args) { String a = “testing”; stringParam(a); System.out.println("String outside method: ” + a); } public static void stringParam(String msg) { msg = msg.toUpperCase(); The location of a is passed into the method, but when the String is modified, the System.out.println("String in method: ” + msg); location is changed! The } method does not change the contents of the String stored in the reference to a. Output String in method: TESTING String outside method: testing 10-12 Comparing Strings == compares if two Strings are stored in the same location in memory equals method compares if contents are the same String s1= “what”; String s2 = new String(“what”); String s3 = “what”; s2==s1 \\false, literal String is stored differently s3==s1 \\true, identical literals saved in same location s2.equals(s1) \\true 10-13 Empty Strings An empty string has no characters; its length is 0. String s1 = ""; Empty strings String s2 = new String(); Not to be confused with an uninitialized string: private String errorMsg; errorMsg is null 14 Constructors String’s no-args and copy constructors are not used much. String s1 = new String (); String s1 = ""; String s2 = new String (s1); String s2 = s1; Other constructors convert arrays into strings. 15 Methods you can use on the AP Exam Strings are IMMUTABLE. No String methods change the original String, they return a new String. Remember you can also concatenate (+) String values 10-16 Methods — length, charAt int length (); Returns the number of characters in the string char charAt (k); Returns the k-th char Character positions in strings are numbered starting from 0 Returns: ”Flower".length(); 6 ”Wind".charAt (2); ’n' 17 Methods — substring String s2 = s.substring (i, k); strawberry returns the substring of chars in positions from i to k-1 i k String s2 = s.substring (i); strawberry returns the substring from the i-th char to the end i Returns: ”strawberry".substring (2,5); "raw" "unhappy".substring (2); "happy" "emptiness".substring (9); "" (empty string) 18 Can call substring method with argument == length of string String s = “cookies”; String s1 = s.substring(7); //empty string String s2 = s.substring(6,7); //holds “s” String s3 = s.substring(7,7); //silly, but holds empty string 10-19 IndexOutOfBoundsException substring(firstArg, secondArg) called with: firstarg length firstarg > secondarg substring(oneArg) called with: oneArglength 10-20 Methods — Concatenation String result = s1 + s2; concatenates s1 and s2 String result = s1.concat (s2); the same as s1 + s2 result += s3; concatenates s3 to result result += num; converts num to String and concatenates it to result 21 Methods — Find (indexOf) 0 8 11 15 String date ="July 5, 2012 1:28:19 PM"; Returns: date.indexOf ('J'); 0 date.indexOf ('2'); 8 date.indexOf ("2012"); 8 date.indexOf ('2', 9); 11 (starts searching at position 9) date.indexOf ("2020"); -1 (not found) date.lastIndexOf ('2'); 15 22 String parameters Strings are objects that holds a reference to their location in memory! BUT: remember that Strings are immutable- when their content is modified the String is saved to a new location public static void main(String[] args) { String a = “testing”; stringParam(a); The location of a is passed into the method and assigned System.out.println("String outside method: ” + a); to msg, but when msg is } changed, the location is changed! The method does not change the contents of public static void stringParam(String msg) { the String stored in the msg = msg.toUpperCase(); reference to a. System.out.println("String in method: ” + msg); } Output String in method: TESTING String outside method: testing Compares two strings lexicographically The comparison is based on the Unicode value of each character in the strings. Each character in a string is given an index (the left most one has index 0). Suppose two strings have different characters at one or more index positions. Example: “today” and “ToDay”. Let k be that smallest index, then the string whose character at position k has the smaller Unicode value, lexicographically precedes the other string. String s = "ab2c"; String s1 = "ab5c"; System.out.println (s.compareTo (s1)); // -5 Can compare alphabetically if all characters in the strings are letters. But some characters are not letters. 24 Methods — Comparisons boolean b = s1.equals(s2); returns true if the string s1 is equal to s2 int diff = s1.compareTo(s2); returns the “difference” s1 - s2. If s1 comes before s2 alphabetically, then s1.compareTo(s2) returns a value which is < 0 (analogy: 4 – 9 = -5. 4 comes before 9 numerically) 25 Review: What makes the String class unusual? How can you include a double quote character into a literal string? Is "length".length() allowed syntax? If so, what is the returned value? Define immutable objects. Does immutability of Strings make Java more efficient or less efficient? 26 Review (cont’d): How do you declare an empty string? Why are String constructors not used very often? If the value of String city is "Boston", what is returned by city.substring(2, 4)? Is s1 += s2 the same as s1 = s1 + s2 for strings? 27 Review (cont’d): What do the indexOf methods do? Name a few overloaded versions. What is more efficient for strings: == and other relational operators or equals and compareTo methods? What does the toString method return for a String object? 28 Review (cont’d): Name a simple way to convert a number into a string. Which class has a method for converting a String into an int? 29 Common Mistakes Using == to test if two strings are equal. This is actually a test to see if they refer to the same object. Usually you only want to know if they have the same characters in the same order. In that case you should use equals or compareTo instead. Treating upper and lower case characters the same in Java. If s1 = "Hi" and s2 = "hi" then s1.equals(s2) is false. Thinking that substrings include the character at the last index when they don’t. Thinking that strings can change when they can’t. They are immutable. Trying to invoke a method like indexOf on a string reference that is null. You will get a null pointer exception. 10-30