Introduction to Strings in Java
Table of Contents + β
In the last lesson you learned about the Java Arrays utility class. The other half of programming is text: names, messages, emails, passwords. In Java, text is handled by a type called the String.
π€ What is a String?
A String is a sequence of characters, which just means a piece of text. Picture a row of letter tiles, like in a word game: each tile holds one character, and the tiles sit in order to spell out the text.
- Holds text, written inside double quotes:
"hello". - Can be any length, from an empty
""to a long paragraph. Stringstarts with a capital S. That is a clue: it is a class, not a basic type likeint.- The characters stay in order, each at a position you read by number.
π§± A String is a reference type, not a primitive
Java has two families of types. Primitives like int, double, char, and boolean, and reference types, which are objects. A String is an object, not a primitive. Think of it like a contact in your phone: the contact is not the person, just a link that points to them.
- A primitive holds the value directly.
int age = 30;means the boxageliterally holds30. - A reference holds a link to an object elsewhere in memory.
String name = "Alex";meansnameholds a pointer to a String object, not the letters. - Because a String is an object, it has methods you call with a dot, like
name.length(). A primitive has none. - Being a reference also explains why comparing Strings needs care (more on that later).
String looks simple, acts special
A String feels as easy to use as int or double. You can write it as plain text in quotes, and Java does not force you to say new. But under that friendly surface, every String is a full object. That is why it carries useful methods like length() and charAt().
βοΈ Creating a String
There are two ways to make a String. The first is a literal: text in double quotes, written right there in the code.
String name = "Alex"; // β
the easy, normal wayString greeting = "Hello, welcome!";String empty = ""; // β
an empty string, zero charactersThe second uses the new keyword, the same way you build any object.
String name = new String("Alex"); // also a String, but rarely needed- Use the literal form (
"Alex") almost always. Shorter, clearer, and Java can reuse identical text to save memory (covered in the string pool lesson). - Use
new String(...)only when you have a reason to force a brand new object. Rarely needed. - Double quotes make a String. Single quotes like
'A'make a singlechar, a different type.
Double quotes for String, single for char
Use double quotes for a String: "A". Use single quotes for one char: 'A'. Writing String letter = 'A'; will not compile, because 'A' is a char, not a String.
π Joining strings with +
You join Strings with the + sign. This is called concatenation: sticking pieces of text end to end.
String first = "Alex";String last = "Kumar";String full = first + " " + last;
System.out.println(full);System.out.println("Welcome, " + first + "!");+glues the pieces into one String.- The
" "in the middle adds a space between first and last name. - You can mix fixed text with variables; the result follows the order you wrote them.
Output
Alex KumarWelcome, Alex!π’ What happens when you join numbers
Here is a part that surprises people. When + has a String on one side, Java treats it as text joining, not math, and turns the number into text. The same + does two different jobs below.
int x = 5;System.out.println("Score: " + x); // text + number β textSystem.out.println(5 + "x"); // number + text β "5x"System.out.println(2 + 3 + "x"); // math first, then textSystem.out.println("x" + 2 + 3); // text first, so no mathReading left to right is the trick to predicting the result:
"Score: " + xjoins text and a number, so5becomes"5":"Score: 5".5 + "x"has a String on the right, so5becomes"5":"5x".2 + 3 + "x"does the math first (2 + 3is5), then5 + "x"is"5x"."x" + 2 + 3already has text on the left, so"x" + 2is"x2", then"x2" + 3is"x23". No math at all.
Output
Score: 55x5xx23So the rule is: + does math only when both sides are numbers. The moment text joins in, everything after it becomes text joining.
π Length and reading one character
Because a String is an object, you can ask it questions. Two you will use constantly:
length()tells you how many characters are in the String.charAt(index)hands you the single character at a given position.
String word = "Java";System.out.println(word.length()); // 4 charactersSystem.out.println(word.charAt(0)); // first characterSystem.out.println(word.charAt(3)); // last characterOne idea you must get right: Java counts positions from zero, not one. This is called zero-based indexing.
- First character is at index
0, second at1, and so on. - Last character is at index
length() - 1, always one less than the length. - For
"Java":Jat 0,aat 1,vat 2,aat 3. Length is 4, last index is 3. - That gap between length and last index causes a very common bug (see below).
Output
4Jaβ¨οΈ Escape sequences inside text
Some characters are hard to type inside quotes: a new line, a tab, or a double quote itself. For these, Java uses an escape sequence: a backslash \ followed by a letter or symbol. The backslash tells Java the next character is special.
System.out.println("Line one\nLine two"); // \n starts a new lineSystem.out.println("Name:\tAlex"); // \t inserts a tab gapSystem.out.println("She said \"hi\""); // \" prints a real quoteSystem.out.println("Path: C:\\Users"); // \\ prints one backslash\nis a newline. It pushes the rest onto the next line.\tis a tab. It adds a wide gap, handy for lining things up.\"prints a double quote. Without the backslash, Java would think the String ended there.\\prints a single backslash, since one alone would be read as an escape.
Output
Line oneLine twoName: AlexShe said "hi"Path: C:\Usersπ Strings are immutable
Here is the rule that surprises almost everyone. A String is immutable: once created, its characters can never be changed. You can point your variable at a new String, but you cannot edit the old one in place.
String name = "Alex";name = name + " Kumar"; // β this does NOT edit "Alex"System.out.println(name);It looks like we changed name, but we did not:
- The original
"Alex"stays exactly as it was. Nothing touched its characters. - The
+builds a brand new String,"Alex Kumar", in a fresh spot in memory. - The variable
nameis then pointed at that new String, and old"Alex"is left behind. - So βchangingβ a String means make a new one, then point the variable at it.
Output
Alex KumarWhy does immutability matter?
Because Strings cannot change, they are safe to share and reuse. Two parts of your program can hold the same text and never worry that one of them will secretly rewrite it. Java also uses this to store identical text efficiently. But there is a cost. Joining text again and again in a big loop creates many throwaway Strings, one per step. That is why Java has StringBuilder for heavy text building, which you will meet in a later lesson.
βοΈ Comparing strings the right way
Comparing Strings has a trap that comes straight from the reference-type idea. Use .equals() to compare the text, not ==.
String a = "hello";String b = "hello";
System.out.println(a.equals(b)); // β
compares the text: trueSystem.out.println(a.equals("HELLO")); // case matters: false.equals()asks βis the text the same?β and returnstruewhen characters match exactly.- It is case-sensitive, so
"hello"and"HELLO"count as different. ==asks βis this the very same object?β, usually not what you want for text.- The string pool lesson shows why
==sometimes seems to work, then fails. Habit: use.equals().
Output
truefalseβ οΈ Common Mistakes
A few String slip-ups to watch for:
- Comparing text with
==.==checks if two variables point to the same object, not whether the letters match. Use.equals()for text.
String a = new String("hi");String b = new String("hi");System.out.println(a == b); // β false, two different objectsSystem.out.println(a.equals(b)); // β
true, same text- Treating a String as if you can edit it. Strings are immutable. A line like
name + " Kumar"builds a new String. If you forget to store it back into a variable, your change just disappears.
String name = "Alex";name + " Kumar"; // β result thrown away, name unchangedname = name + " Kumar"; // β
store the new String back- Reading past the end with an index. Remember the last valid index is
length() - 1. Asking forcharAt(length())runs off the end and crashes with aStringIndexOutOfBoundsException.
String word = "Java"; // length is 4System.out.println(word.charAt(4)); // β no index 4, crashesSystem.out.println(word.charAt(3)); // β
last valid index- Using single quotes for text.
"hello"is a String.'h'is a singlechar. Text needs double quotes.
β Best Practices
Habits for working with Strings:
- Compare text with
.equals(). Reach for==only when you truly mean βthe same objectβ. - Prefer the literal form. Write
"Alex", notnew String("Alex"), unless you have a clear reason. - Remember immutability, and store the result. Each βchangeβ makes a new String, so always assign it back:
name = name + " Kumar";. - Mind zero-based indexing. First character is at
0, last is atlength() - 1. Check the edges before you callcharAt(). - Use clear names.
name,message,email. The name should say what text it holds.
π§© What Youβve Learned
Nicely done. A quick recap:
- β A String is a sequence of characters, that is, a piece of text, written in double quotes.
- β A String is a reference type (an object), not a primitive. That is why it has methods you call with a dot.
- β
There are two ways to create one: the literal
"hi"(use this) andnew String("hi")(rarely needed). - β
Join Strings with
+(concatenation). Once text joins in, numbers become text too, read left to right. - β
length()counts characters, andcharAt(index)reads one, with zero-based positions. - β
Escape sequences like
\n,\t, and\"put special characters inside text. - β Strings are immutable: a βchangeβ really makes a new String and points the variable at it.
- β
Compare text with
.equals(), not==.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
How do you write a String value in Java?
Why: Strings use double quotes; single quotes are for a single char.
- 2
What does it mean that a String is immutable?
Why: An immutable String never changes; operations build a new String instead.
- 3
What does name + " Kumar" do to the original String in name?
Why: Strings are immutable, so + creates a new String; the original is untouched.
- 4
How should you compare the text of two Strings?
Why: .equals() compares the actual characters; == only checks if it is the same object.
π Whatβs Next?
Next, letβs look at how Java stores Strings behind the scenes. The string pool lets Java reuse identical text to save memory, and it explains why == sometimes seems to work.