80 likes | 316 Views
Intro to CS – Honors I Java Strings. Georgios Portokalidis gportoka@stevens.edu. Strings of Characters. Strings are not a primitive type in Java c lass String A string variable is defined as: String greeting; String constants are enclosed between double quotes
E N D
Intro to CS – Honors IJava Strings Georgios Portokalidis gportoka@stevens.edu
Strings of Characters • Strings are not a primitive type in Java • class String • A string variable is defined as: String greeting; • String constants are enclosed between double quotes • + can be used to concatenate two strings • greeting = "Hello"; • sentence = greeting + "my friend"; "Hellomy friend“ • + does not also add a space between the concatenated strings
String Methods • String is a class, so it has methods • Methods of an object are called using . And () • String greeting = "Hello"; • int n = greeting.length( ); • Constants are also objects of type class String “Hello”.length() is valid • Can you find other methods of String using Java’s API documentation? • The object used with a method is called a receiving object
String as Arrays • String “Hello World” • Other methods • Index of substring indexOf(“World”) 7 Character indices Whitespace: includes space, tab, and new-line characters.
String are Immutable • Strings cannot be changed! • However, it can be reassigned • Example: • String name = “Potter”; • name = “Harry “ + name; • name = name.substring(0, name.indexOf(“Potter”)) + “Truman” • Modifiable strings are available through the StringBuilder class
Escape Characters • How do you insert double quotes in a string? • Example: The word "Java" names a language, not just a drink! • Special characters can be inserted into strings by prefixing them with backslash (\) • “The word \"Java\" names a language, not just a drink!” Why escape the single quote?
Unicode Character Set • What would the following print? • char symbol = '7'; • System.out.println((int)symbol); • Each character corresponds to a number • Unicode: 2 bytes • ASCII: 1 bytesUnicode • You can cast a char to int, but it is not advisable