Also known as text.
They are not a primitive type but they do get some special support in the language.
"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.
Smoosh them together
Take them apart
Make related strings
+ operator works on stringsAlso known as “concatenation”
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.
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.
length method
Strings have a length() method that returns the number
of characters in the 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 methodSometimes we want to extract a chunk of a string.
Strings have a substring method for this.
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"f = "foo"f.substring(0, 1).toUpperCase() + f.substring(1)
"Foo"
Returns the position of the first occurrence of the given string,
"a" in this case, in the string it is invoked on.
Can use this fact to test whether a character is in a string.
If s is a string
s.substring(1) is also a string
s.substring(1).toUpperCase()
"foo" + "bar".toUpperCase()
⟹ "fooBAR"
("foo" + "bar").toUpperCase()
⟹ "FOOBAR"
String s = "Foo";
s + s ⟹ "FooFoo"
s.substring(0, 1) ⟹ "F"
s.length() ⟹ 3
s.toUpperCase() ⟹ "FOO"
s.toLowerCase() ⟹ "foo"
s.indexOf("o") ⟹ 1