Strings

Also known as text.

Strings are yet another kind of value

They are not a primitive type but they do get some special support in the language.

Literal strings.

"foo"

"this is a string with spaces"

Note that the quotation marks are not part of the string.

"foo" is three characters long, not five.

What can we do with strings?

  • Smoosh them together

  • Take them apart

  • Make related strings

The + operator works on strings

Also known as “concatenation”

» "foo" + "bar"
"foobar"

⚠️ Watch out though ⚠️

When asked to add different types of values, and one of them is a string, Java will convert the other one to a string and then concatenate them.

» 1 + "0"
"10"

Indexes

a.k.a. “indices”

Identify characters within the string by their position.

The index of the first character is 0.

This is called a zero-based index.

Think of it as how many characters are ahead of the given character.

The length method

Strings have a length() method that returns the number of characters in the String.

» "foobar".length()
6

Valid indices for a string s

If the index of the first character is 0 what is the last valid index?

s.length() - 1

There is no character in the string that has length() characters ahead of it.

substring method

Sometimes we want to extract a chunk of a string.

Strings have a substring method for this.

Extracts a substring

From a starting index (inclusive) to an end index (exclusive)

s.substring(start index, end index)

or

s.substring(start index)

Second argument is implicitly s.length().

s = "foobar"

» s.substring(0)
"foobar"

» s.substring(1)
"oobar"

» s.substring(s.length() - 1)
"r"

» s.substring(s.length())
""

» s.substring(0, 3)
"foo"

» s.substring(3)
"bar"

» s.substring(3, s.length())
"bar"

Some other useful String methods

» "foo".toUpperCase()
"FOO"

» "FOO".toLowerCase()
"foo"

f = "foo"

f.substring(0, 1).toUpperCase() + f.substring(1)
"Foo"

» "foobar".indexOf("a")
4

Returns the position of the first occurrence of the given string, "a" in this case, in the string it is invoked on.

» "foobar".indexOf("z")
-1

Can use this fact to test whether a character is in a string.

Chaining methods

If s is a string

s.substring(1) is also a string

s.substring(1).toUpperCase()

Can use any string expression

"foo" + "bar".toUpperCase()
⟹ "fooBAR"

("foo" + "bar").toUpperCase()
⟹ "FOOBAR"

Cheat sheet

String s = "Foo";

s + s"FooFoo"

s.substring(0, 1)"F"

s.length() ⟹ 3

s.toUpperCase()"FOO"

s.toLowerCase()"foo"

s.indexOf("o") ⟹ 1