1 / 8

Intro to CS – Honors I Java Strings

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

caelan
Download Presentation

Intro to CS – Honors I Java Strings

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Intro to CS – Honors IJava Strings Georgios Portokalidis gportoka@stevens.edu

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

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

  4. String as Arrays • String “Hello World” • Other methods • Index of substring indexOf(“World”)  7 Character indices Whitespace: includes space, tab, and new-line characters.

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

  6. 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?

  7. 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 bytesUnicode • You can cast a char to int, but it is not advisable

More Related