Meet your first object in Java.
One machine can build many different robots.
Use the same machine, but change the settings each time.
A class is the plan, and an object is one real example.
String"Hello"Some variables store values, and some store references.
int, double, and boolean store the value itself. String is your first important reference type in AP CSA. Primitive values sit in the variable directly; reference variables point to the object.
Now treat text in Java as an object.
String is the class name for this kind of text object. new String("Hello") creates one real string object. length() on it. Start with new, then compare the shorter form.
new tells Java to create a fresh object. "Hello" is the shorter form for the same kind of object. Use + to build a new string from smaller pieces.
+ joins two strings into one new result. In the later questions, pay close attention to when text appears.
Use the dot operator to call a method on one object.
word. Common String methods at a glance.
Use length() when you need the number of characters.
int with the string's character count. "coding" has 6 characters. Indexes start at 0 and stop at length minus 1.
0. length() - 1. StringIndexOutOfBoundsException. Use indexOf() to find where a piece of text first appears.
int index, or -1 if not found. "d" in "coding" is at index 2. -1. Take the part from from up to to - 1.
from is included. to is not included. substring(1, 4) gives "odi". Take everything from one index to the end.
substring(2) gives "ding". Use substring(index, index + 1) to make a one-letter string.
index + 1 so only one character is included. String, just with length 1. Use equals() to check whether two strings have the same text.
boolean: either true or false. "coding", so Java returns true. equals(). Use compareTo() when you want alphabetical order.
Use split() to break one string into smaller pieces.
String[] with several pieces. "i" gives "cod" and "ng". split() more later, so just keep the big idea for now. For each code sample, decide what is printed.
String methods usually return a new result.
word.substring(0, 3) alone does not replace the old string. word = word.substring(0, 3) to keep the new text. A reference can also point to no object.
"" is a real string object, so its length is 0. null means the variable is connected to no object. length() on "", but not on null. Now decide what happens after the method call.
As a supplement, see how familiar classes fit into one larger family.
One more supplement: String is built in, and objects can join strings too.
String is built in, so Java gives it to you automatically. toString(). Key ideas from today
A class is a blueprint. An object is one real instance.
String uses a reference, and that reference can also be null.
Call string methods with the object name, a dot, and the method name.
String methods return new results, so save the new string when you want to keep it.