Download presentation
Presentation is loading. Please wait.
Published byRosemary Richards Modified over 9 years ago
1
John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:
2
Strings A String consists of zero or more characters String is a class that contains many methods Strings are more complicated than they sound!
3
3 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";
4
4 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";
5
5 Trace Code String s = "Java"; s = "HTML"; animation
6
6 Trace Code String s = "Java"; s = "HTML"; animation
7
7 Interned Strings Since strings are immutable and are frequently used, to improve efficiency and save memory, the JVM uses a unique instance for string literals with the same character sequence. Such an instance is called interned. For example, the following statements:
8
8 Examples display s1 == s2 is false s1 == s3 is true A new object is created if you use the new operator. If you use the string initializer, no new object is created if the interned object is already created.
9
9 Trace Code animation
10
10 Trace Code
11
11 Trace Code
12
12 String Comparisons
13
13 String Comparisons equals String s1 = new String("Welcome“); String s2 = "welcome"; if (s1.equals(s2)){ // s1 and s2 have the same contents } if (s1 == s2) { // s1 and s2 have the same reference }
14
14 String Comparisons, cont. compareTo(Object object) String s1 = new String("Welcome"); String s2 = "welcome"; if (s1.compareTo(s2) > 0) { // s1 is greater than s2 } else if (s1.compareTo(s2) == 0) { // s1 and s2 have the same contents } else // s1 is less than s2
15
public class StringDemo{ public static void main(String[] args){ String s1 = new String("Welcome"); String s2 = "welcome"; String s3 = s1; String s4 = new String("Welcome"); if (s1.equals(s2)){ System.out.println("s1 equals s2"); } else System.out.println("s1 does not equal s2"); if (s1 == s2) { System.out.println("s1 == s2"); } else System.out.println("s1 != s2"); if (s1.equals(s3)){ System.out.println("s1 equals s3"); } if (s1 == s3) { System.out.println("s1 == s3"); } else System.out.println("s1 != s3"); if (s1.equals(s4)){ System.out.println("s1 equals s4"); } else System.out.println("s1 does not equal s4"); if (s1 == s4){ System.out.println("s1 == s4"); } else System.out.println("s1 != s4"); if (s1.compareTo(s2) < 0) { System.out.println("s1 < s2"); }
16
16 String Length, Characters, and Combining Strings
17
17 Finding String Length Finding string length using the length() method: message = "Welcome"; message.length() (returns 7 )
18
18 Retrieving Individual Characters in a String Do not use message[0] Use message.charAt(index) Index starts from 0
19
19 String Concatenation String s3 = s1.concat(s2); String s3 = s1 + s2; s1 + s2 + s3 + s4 + s5 same as (((s1.concat(s2)).concat(s3)).concat(s4)).concat(s5);
20
Strings public static void main(String[] args){ String s1 = new String("Welcome"); String s2 = " Shriners"; String s3 = s1.concat(s2); System.out.println(s3); String s4 = s1 + s2; System.out.println(s4); s1 = s1 + s2; System.out.println(s1); if(s1.startsWith("Wel")) System.out.println("\"" + s1 + "\"" + " starts with \"Wel!\""); System.out.println("Length of \"" + s1 + "\" is " + s1.length()); System.out.println("In the string \"" + s1 + "\", the character at position 4 is " + s1.charAt(4)); }
21
21 Extracting Substrings
22
22 Extracting Substrings You can extract a single character from a string using the charAt method. You can also extract a substring from a string using the substring method in the String class. String s1 = "Welcome to Java"; String s2 = s1.substring(0, 11) + "HTML";
23
23 Converting, Replacing, and Splitting Strings
24
24 Examples "Welcome".toLowerCase() returns a new string, welcome. "Welcome".toUpperCase() returns a new string, WELCOME. " Welcome ".trim() returns a new string, Welcome. "Welcome".replace('e', 'A') returns a new string, WAlcomA. "Welcome".replaceFirst("e", "AB") returns a new string, WABlcome. "Welcome".replace("e", "AB") returns a new string, WABlcomAB. "Welcome".replace("el", "AB") returns a new string, WABlcome.
25
25 Splitting a String String[] tokens = "Java#HTML#Perl".split("#", 0); for (int i = 0; i < tokens.length; i++) System.out.print(tokens[i] + " "); Java HTML Perl displays
26
26 Finding a Character or a Substring in a String
27
27 Finding a Character or a Substring in a String "Welcome to Java".indexOf('W') returns 0. "Welcome to Java".indexOf('x') returns -1. "Welcome to Java".indexOf('o', 5) returns 9. "Welcome to Java".indexOf("come") returns 3. "Welcome to Java".indexOf("Java", 5) returns 11. "Welcome to Java".indexOf("java", 5) returns -1. "Welcome to Java".lastIndexOf('a') returns 14.
28
public class StringDemo5{ public static void main(String[] args){ String theString = "The baby fell out of the window\nI thought that her head would be split\nBut good luck was with us that morning\n" + "For she fell in a bucket of #$%*!\n\nHere we are in this fancy French restaurant\nI hate to be raising a snit\nBut waiter, I ordered cream vichysoisse\nand you " + "brought me a bowl full of #$%*!\n\n"; System.out.println("\nOld:\n" + theString); String newString = theString.replace("#$%*!", "shaving cream\nBe nice and clean\nShave every day and you'll always look keen!\n"); System.out.println("New:\n" + newString); }
29
public class StringDemo3{ public static void main(String[] args){ String theString = "'Take some more tea,' the March Hare said to Alice, very earnestly.\n\n'I've had nothing yet,' Alice replied in " + "an offended tone, 'so I can't take more.'\n\n'You mean you can't take LESS,' said the Hatter: 'it's very easy to take MORE than nothing.'" + "\n\n'Nobody asked YOUR opinion,' said Alice."; System.out.println("\n" + theString); System.out.println("\n\nall lower case: " + theString.toLowerCase() + "\n"); System.out.println("\n\nsubstring from index 3 to end: " + theString.substring(3) + "\n"); System.out.println("\n\nsubstring starting at index 24, ending at 30: " +theString.substring (24, 30) + "\n"); System.out.println("character at index 39 is: " + theString.charAt(39) + "\n"); System.out.println("\n\nfirst y is at: " + theString.indexOf('y')); System.out.println("\n\nsubstring from first y to last y: " + theString.substring(theString.indexOf('y'), theString.lastIndexOf('y'))); }
30
30 StringBuilder The StringBuilder class is a supplement to the String class. StringBuilder is more flexible than String. You can add, insert, or append new contents into a string buffer, whereas the value of a String object is fixed once the string is created. You will often have to parse the StringBuilder to a String when you are done constructing it.
31
31 StringBuilder Constructors
32
32 Modifying Strings in the Builder
33
33 The toString, capacity, length, setLength, and charAt Methods
34
34 Examples stringBuilder.append("Java"); stringBuilder.insert(11, "HTML and "); stringBuilder.delete(8, 11) changes the builder to Welcome Java. stringBuilder.deleteCharAt(8) changes the builder to Welcome o Java. stringBuilder.reverse() changes the builder to avaJ ot emocleW. stringBuilder.replace(11, 15, "HTML") changes the builder to Welcome to HTML. stringBuilder.setCharAt(0, 'w') sets the builder to welcome to Java.
35
Strings Consider the chorus of the Irish song “Rare Old Mountain Dew”: diddly eidel diddle dum diddly eidel diddly eidel dum day diddly eidel diddle dum diddly eidel diddly eidel dum day This contains several substrings that are repeated How can we generate this using loops?
36
Strings and StringBuilders public class MountainDew{ public static void main(String[] args){ String diddly = "diddly eidel"; String diddle = "diddle dum"; String dum = "dum day"; StringBuilder sb = new StringBuilder(); for(int counter = 0; counter < 2; counter++){ for(int counter2 = 0; counter2 <= 3; counter2++){ sb.append(diddly + " "); if(counter2 < 2) { sb.append(diddle); sb.append("\n"); } else if(counter2 == 3) sb.append(dum); } if(counter == 0) sb.append("\n\n"); } System.out.println(sb); }
37
StringBuilder public class StringBuilderDemo{ public static void main(String[] Args){ StringBuilder sb = new StringBuilder("Bakey"); System.out.println(sb); sb.insert(4, "ry"); System.out.println(sb); sb.deleteCharAt(5); System.out.println(sb); // this will not do what you expect! sb.append(" " + sb.reverse()); System.out.println(sb); sb.delete(sb.indexOf(" "), sb.length()); System.out.println(sb); StringBuilder sb2 = new StringBuilder(sb); sb.deleteCharAt(5); sb2.reverse(); sb.append(sb2); System.out.println(sb); sb.insert(5," "); System.out.println(sb); sb.replace(0,0,"Y"); System.out.println(sb); sb.deleteCharAt(1); System.out.println(sb); sb.reverse(); System.out.println(sb); }
38
Dialog Boxes GUI construction is taught in CS202, but we will cover a few GUI rudiments in 201 The first is the JOptionPane class, which provides pop-up I/O boxes of several kinds Need to include this at the very top of your class: import javax.swing.JOptionPane; JOptionPane.showMessageDialog() displays a dialog box with text you specify
39
Dialog Boxes import javax.swing.JOptionPane; public class DialogBox{ public static void main(String[] args){ for(int i = 0; i < 4; i++){ JOptionPane.showMessageDialog(null, "This is number " + i); }
40
Dialog Boxes JOptionPane.showInputDialog() shows a dialog box that can take input The input is a String We will learn soon how to parse from String to other types
41
Dialog Boxes import javax.swing.JOptionPane; public class InputBox{ public static void main(String[] args){ String input = JOptionPane.showInputDialog(null, "Please enter some input "); JOptionPane.showMessageDialog(null, "You entered: \"" + input + "\""); String input2 = input.concat(" " + JOptionPane.showInputDialog(null, "Please enter some more input ")); JOptionPane.showMessageDialog(null, "You entered: \"" + input2 + "\""); }
42
Casting Strings to Numeric Types Recall that input from JOptionPane.showInputDialog is a String Cast to integer: Integer.parseInt(intString); Example: String input = int age = Integer.parseInt(JOptionPane. showInputDialog(null, “Please enter your age”); Cast to double: Double.parseDouble(doubleString);
43
Casting to Numeric Types Note the capitalization in the method names. Double and Integer are not quite the same as double and integer. You’ll understand when you are a little older…
44
Parsing to Integer import javax.swing.JOptionPane; public class NumericCastDemo{ public static void main(String[] args){ int age = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter your age")); if(age < 30) JOptionPane.showMessageDialog(null, age + " is pretty young."); else if(age > 100) JOptionPane.showMessageDialog(null, "really?"); else JOptionPane.showMessageDialog(null, "That's OK. Methuseleh lived to be " + (270 - age) + " years older than you are now."); } // end main() } // end class
45
Parsing to Double import javax.swing.JOptionPane; public class NumericCastDemo{ public static void main(String[] args){ double age = Double.parseDouble(JOptionPane.showInputDialog(null, "Please enter your age")); if(age < 30) JOptionPane.showMessageDialog(null, age + " is pretty young."); else if(age > 100) JOptionPane.showMessageDialog(null, "really?"); else JOptionPane.showMessageDialog(null, "That's OK. Methuseleh lived to be " + (270 / age) + " times as old as you are now."); } // end main() } // end class
46
Imports We have already discussed javax.swing.JOptionPane methods to show input and message dialogs These required the following line at the top of the class: Import javax.swing.JOptionPane; If you omit this line, you will get an error message like this: SwitchDemo.java: 7: cannot find symbol Symbol:variable JOptionPane
47
Imports Java classes are organized in packages Late in this class or early in CS202 you will start using packages for multiple classes Javax.swing is a package of GUI-related classes that is included with all distributions of Java JOptionPane is a class within this package JOptionPane.showMessageDialog() and JOptionPane.showInputDialog are methods of the class
48
Imports Including a package in your program adds a small cost, slowing down the compiler as it looks through the imported package Thus, things like javax.swing are not included automatically; you must specify that you need them You will eventually be importing your own packages, too. Don’t leave unused imports in your code
49
public class ValueOfDemo{ public static void main(String[] args){ double d = 1234.56789; // this would cause an error: int precision=d.indexOf('.'); String stringD = String.valueOf(d); int stringLength = stringD.length(); int locationOfDecimalPoint = stringD.indexOf("."); System.out.println("length of string " + stringD + " is " + stringLength + " location of decimal point is " + locationOfDecimalPoint); int precision = stringLength - locationOfDecimalPoint -1; System.out.println(precision + " digits after the decimal point"); }
50
Validating Data Type We have already discussed how to make sure that numeric input from Scanner is within a desired range int age; do { System.out.println("How old are you?"); age = sc.nextInt(); } while (age 100);
51
Validating Scanner Input So far, our programs have crashed if casts to numeric types failed: Try this with input “two point five”: import java.util.Scanner; public class ReadDouble2 { public static void main(String[] args) { Scanner input = new Scanner(System.in); Double stuff = 0.0; do { System.out.print("Input a double. Enter 0 to quit:"); stuff = input.nextDouble(); System.out.println("\nYou entered: " + stuff); } while (stuff != 0.0); }
52
Validating Scanner Input Here is the simplest way to validate Scanner input for data type (that is, to make sure you get input that can be cast to double, integer, etc.) Scanner has hasNext…() methods that see if there is a parseable token hasNextInt() hasNextDouble() hasNextBoolean() Also need next() to skip over bad input
53
Validating Scanner Input Try this one with input “nine.three”, then with input “nine point three: import java.util.Scanner; public class ReadDouble3 { public static void main(String[] args) { Scanner input = new Scanner(System.in); Double inpDouble = 10.0; // bad code ahead!! do { System.out.print("Input a double. Enter 0 to quit:"); if(input.hasNextDouble()){ inpDouble = input.nextDouble(); System.out.println("\nYou entered: " + inpDouble); } else input.next(); } while (inpDouble != 0.0); }
54
Validating Scanner Input In order to get good output, we need to arrange things in a slightly more complex way: import java.util.Scanner; public class ReadInt{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int x; System.out.println("Enter an integer"); while (!sc.hasNextInt()) { sc.nextLine(); System.out.println("No, an integer!"); } x = sc.nextInt(); System.out.println(x); }
55
55 Convert Character and Numbers to Strings The String class provides several static valueOf methods for converting characters, arrays of characters, and numeric values to Strings. These methods are named valueOf with different argument types char, char[], double, long, int, and float. For example, to convert a double value to a string, use String.valueOf(5.44). The return value is string consists of characters ‘5’, ‘.’, ‘4’, and ‘4’.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.