Presentation is loading. Please wait.

Presentation is loading. Please wait.

John Hurley Cal State LA

Similar presentations


Presentation on theme: "John Hurley Cal State LA"— Presentation transcript:

1 John Hurley Cal State LA
CS 201 Lecture 6: John Hurley Cal State LA

2 Character Codes Computers store information in bits, not as characters
Numeric values are easy to map to bits; just convert them to base 2 and then map each digit to a bit There are several code systems to assign numeric values to characters

3 Character Codes ASCII developed in the early 1960s, when memory was much more expensive than it is now. Originally used to send teletype data over phone lines, which are noisy 128 (27) possible characters The first 33 are control characters, originally used to control teletypes

4 Character Codes Unicode Used in Java Superset of ASCII 65536 values
The first 128 are the same as ASCII Adds other alphabets, mathematical symbols,etc.

5 Unicode and Hardware

6 Character Codes public class ASCIIUnicodeDemo{
public static void main(String[] args){ for(int charNum = 0; charNum < 128; charNum++){ System.out.println("Character " + charNum + " is " + (char) charNum); } Why do we get a blank line after 10 and before 11?

7 Character Codes chars can be compared using <, =, > operators
Apply the math operators to the Unicode values It’s probably obvious that ‘a’ < ‘b’ Not obvious that ‘A’ < ‘a’ ‘0’ < ‘a’ ‘/’ < ‘a’ 8 < ‘5’ !!

8 Character Codes public class UnicodeCompare{ public static void main(String[] args){ for(int charNum = 0; charNum < 128; charNum++){ char currChar = (char) charNum; System.out.println("'" + currChar + "': " + " less than 'A'? " + (currChar < 'A')); } System.out.println("And by the way, it is " + (8 < '5') + " that 8 < '5'");

9 Strings A String consists of zero or more characters
String is a class that contains many methods Strings are more complicated than they sound!

10 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";

11 Variables vs Objects Consider this code: int myInt = 1; 1 is a value
myInt is a variable String s1 = "The moon is made of green cheese." "The moon is made of green cheese" is a String, an object of class String. s1 is a variable

12 Null A null value is one that does not exist. Variables whose data type is a class, like String, may exist without having any value: String s = null; A variable whose type is a primitive data type will be null if no value is set, but can't be set to null int x; // ok int x = null; //syntax error

13 Strings Are Immutable A String object is immutable; its contents cannot be changed. The following code does not change the contents of the String, it makes the variable s point to a different String in memory. String s = "Java"; s = "HTML";

14 animation Trace Code String s = "Java"; s = "HTML";

15 animation Trace Code String s = "Java"; s = "HTML";

16 Interned Strings Since strings are immutable, if two different variables need to point to identical Strings, there is no need to save two separate Strings in memory. The JVM usually uses a unique instance for each set of string literals with the same character sequence. In other words, the following code sets up one String in memory, but two variables that point to it: String s1 = "John"; String s2 = "John"; Such an instance is said to be interned. If you set up a new String using the full new String syntax, however, the JVM will not use an interned String even if there is one with identical text. This code sets up two separate Strings with identical characters: String s1 = "John"' String s2 = new String("John");

17 Examples s1 == s2 is false, because the == operation for Strings tests whether two Strings are the same object in memory, and we did not use the interned String s1 == s3 is true because without the new String() syntax, we used the interned String. Thus, s1 and s3 point to the same object in memory.

18 animation Trace Code

19 Trace Code

20 Trace Code

21 String Comparisons .equals(String otherString) test whether the text of this String is the same as the text of the other String

22 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 memory reference

23 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

24 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");

25 Escape Sequences Some characters will cause confusion in output
What will happen if we try to execute this: System.out.println(""Hi,Mom""); Others, like backspace and tab, can’t be unambiguously typed Use escape characters for these cases

26 Escape Sequences Description Escape Sequence Backspace \b Tab \t
Linefeed \n Carriage return \r (think of a typewriter) Backslash \\ Single Quote \' Double Quote \"

27 Escape Sequences } public class EscapeDemo{
public static void main(String[] args) { System.out.println("A\tB\rB\tC D\nDD\b E\\F \'Hi, Mom\' \"Hi, Mom\""); System.out.println("She said \"They tried to make me go to rehab, but I said \"No, No, No!\"\""); }

28 String Concatenation Appending a String or character to the end of another String is called concatenation. Three strings concatenated: String message = "Welcome " + "to " + "Java"; String s1 concatenated with character B: String s1 = "Supplement" + 'B'; // s1 becomes SupplementB To concatenate to existing String, create a new String and use concat(): String myString = "Good"; String myOtherString = myString.concat(" Morning");

29 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);

30 String Length, Characters, and Combining Strings

31 Finding String Length message = "Welcome";
Finding string length using the length() method: message = "Welcome"; message.length() (returns 7)

32 Retrieving Individual Characters in a String
Do not use message[0] Use message.charAt(index) Index starts from 0

33 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)); }

34 Extracting Substrings

35 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";

36 Converting, Replacing, and Splitting Strings

37 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.

38 Finding a Character or a Substring in a String

39 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.

40 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\nFor 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 creamed 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); }

41 public static void main(String[] args){
String theString = "'Take some more tea,' the March Hare said to Alice, very earnestly.\n'I've had nothing yet,' Alice replied in " + "an offended tone, 'so I can't take more.'\n'You mean you can't take LESS,' said the Hatter: 'it's very easy to take MORE " + "than nothing. \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 just before last y: " + theString.substring(theString.indexOf('y'), theString.lastIndexOf('y'))); }

42 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.

43 StringBuilder Constructors

44 Modifying Strings in the Builder

45 The toString, capacity, length, setLength, and charAt Methods

46 Examples public static void main(String[] args) {
StringBuilder stringBuilder = new StringBuilder("Welcome to "); System.out.println(stringBuilder); stringBuilder.append("Java"); stringBuilder.insert(11, "HTML and "); stringBuilder.delete(8, 11); // changes the builder to Welcome HTML and Java. stringBuilder.deleteCharAt(8); // changes the builder to Welcome TML and Java. stringBuilder.reverse(); // changes the builder to avaJ dna LMT emocleW stringBuilder.reverse(); // undoes the reverse() stringBuilder.replace(11, 15, " to"); // changes the builder to Welcome TML to Java. stringBuilder.delete(7,11); // back to Welcome to Java stringBuilder.setCharAt(0, 'w'); // sets the builder to welcome to Java. }

47 StringBuilder public class StringBuilderDemo{ public static void main(String[] Args){ StringBuilder sb = new StringBuilder("Bakey"); System.out.println(sb); sb.insert(4, "ry"); sb.deleteCharAt(5); // this will not do what you expect! sb.append(" " + sb.reverse()); sb.delete(sb.indexOf(" "), sb.length()); StringBuilder sb2 = new StringBuilder(sb); sb2.reverse(); sb.append(sb2); sb.insert(5," "); sb.replace(0,0,"Y"); sb.deleteCharAt(1); sb.reverse(); }


Download ppt "John Hurley Cal State LA"

Similar presentations


Ads by Google