120 likes | 215 Vues
Strings Are Important. The String class is one of the most important supplied classes with Java. Besides int and doubles we use chars (single characters) and Strings (multiple characters) the most. Strings are an abstract data type in Java (cf. primitive data types). java.lang.
E N D
Strings Are Important • The String class is one of the most important supplied classes with Java. • Besides int and doubles we use chars (single characters) and Strings (multiple characters) the most. • Strings are an abstract data type in Java (cf. primitive data types)
java.lang • They are part of the java.lang package. • A String is a sequence of characters. • Because it’s a sequence, it has an order… • that is, a beginning, a middle, and an end.
String sequences • Each character in a string can be identified by its sequential position. • This position is a number called the index. • The 1st character in a string has an index of zero (0). • This is weird but universal in programming languages.
My Favourite String • Imagine the string “billy”. • Note that billy has 5 characters but that the highest index is 4. • That’s because the index begins at 0. • The index of the last character is the length -1. • This is a big “gotcha”.
Spaces Are Characters Too • The string “billy billy billy.” is 18 characters long. • Why? • Because the spaces count as characters. • So does the period.
String Methods • Java supplies numerous methods to deal with strings. • See p138 in your text. • Lets focus on a couple of key String methods. • Assume: String phrase = “billy”; • length() • System.out.println(phrase.length()); prints 5.
String Methods • toLowerCase() returns a copy of the string with all lower case letters. • System.out.println (phrase.toLowerCase()); prints billy. • toUpperCase() returns a copy of the string with all upper case letters. • System.out.println (phrase.toUpperCase()); prints BILLY.
String Methods • replaceFirst(String str, String str2) returns a string with the 1st occurrence of str replaced by str2. • System.out.println (phrase.replaceFirst(“ill”, “obb”)); prints bobby. • str and str2 do not have to be the same length. • cf. replaceAll(String str, String str2)
String Methods • You need to know all the methods on P138 for the test. • N.B. when we say that a method returns something we mean that the thing which is returned completely replaces the program code that was there before. • So if you assign the result of a method to a variable it must have the right data type.
You Do. • P139: Review: AccountSetup
String Methods (comparison) • Some of the most important methods have to do with comparing strings. • We cannot compare strings using the standard relational operators (<, <=, ==, >, >=). • We must use special String comparison methods instead. • See P140 for a list of important String comparison methods. • Let’s go over the list together.
You Do • P141: Review: FormalGreeting