Java Notes
String represents text in Java. A String is an immutable sequence of characters used for names, messages, paths, URLs, and every other piece of text in a program.
String is Java's built-in type for text. It belongs to java.lang, so no import is needed. A String is an object, not a character array that your program can freely change.
Create a String
Use a string literal for ordinary text. It is concise and lets Java reuse identical literal values through the String Pool.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
student is created with a literal. course is created explicitly with new; this is valid, but usually unnecessary. Prefer literals unless an API gives you characters or bytes to convert.
String Pool and comparison
Java stores string literals in a shared pool. When the same literal occurs again, Java can reuse that object. This saves memory, but it also explains why == and equals() have different jobs.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
== asks whether two variables refer to the same object. equals() asks whether the text is the same. For user-facing text, names, passwords, input, and values from files, use equals().
Useful operations
String methods return a new String because String objects are immutable.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
trim() removes edge spaces, length() counts characters, toUpperCase() changes letter case in a new value, substring() extracts part of the text, and contains() checks for text. The original title remains unchanged.
When to use String
Use String for text that is mostly read: labels, identifiers, URLs, messages, configuration values, and JSON fields. For building a long string inside a loop, use StringBuilder; it avoids creating a new String for every append.
Common mistake
Do not compare text with ==. It may appear to work with two literals, then fail when one value comes from input or new String(...). Compare content with first.equals(second), or use "known value".equals(maybeNull) when the second value could be null.
Continue the lesson path