Introduction to Strings in Java

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.
  • String starts with a capital S. That is a clue: it is a class, not a basic type like int.
  • 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 box age literally holds 30.
  • A reference holds a link to an object elsewhere in memory. String name = "Alex"; means name holds 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 way
String greeting = "Hello, welcome!";
String empty = ""; // βœ… an empty string, zero characters

The 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 single char, 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 Kumar
Welcome, 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 β†’ text
System.out.println(5 + "x"); // number + text β†’ "5x"
System.out.println(2 + 3 + "x"); // math first, then text
System.out.println("x" + 2 + 3); // text first, so no math

Reading left to right is the trick to predicting the result:

  • "Score: " + x joins text and a number, so 5 becomes "5": "Score: 5".
  • 5 + "x" has a String on the right, so 5 becomes "5": "5x".
  • 2 + 3 + "x" does the math first (2 + 3 is 5), then 5 + "x" is "5x".
  • "x" + 2 + 3 already has text on the left, so "x" + 2 is "x2", then "x2" + 3 is "x23". No math at all.

Output

Score: 5
5x
5x
x23

So 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 characters
System.out.println(word.charAt(0)); // first character
System.out.println(word.charAt(3)); // last character

One 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 at 1, and so on.
  • Last character is at index length() - 1, always one less than the length.
  • For "Java": J at 0, a at 1, v at 2, a at 3. Length is 4, last index is 3.
  • That gap between length and last index causes a very common bug (see below).

Output

4
J
a

⌨️ 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 line
System.out.println("Name:\tAlex"); // \t inserts a tab gap
System.out.println("She said \"hi\""); // \" prints a real quote
System.out.println("Path: C:\\Users"); // \\ prints one backslash
  • \n is a newline. It pushes the rest onto the next line.
  • \t is 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 one
Line two
Name: Alex
She 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 name is 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 Kumar

Why 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: true
System.out.println(a.equals("HELLO")); // case matters: false
  • .equals() asks β€œis the text the same?” and returns true when 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

true
false

⚠️ 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 objects
System.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 unchanged
name = name + " Kumar"; // βœ… store the new String back
  • Reading past the end with an index. Remember the last valid index is length() - 1. Asking for charAt(length()) runs off the end and crashes with a StringIndexOutOfBoundsException.
String word = "Java"; // length is 4
System.out.println(word.charAt(4)); // ❌ no index 4, crashes
System.out.println(word.charAt(3)); // βœ… last valid index
  • Using single quotes for text. "hello" is a String. 'h' is a single char. 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", not new 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 at length() - 1. Check the edges before you call charAt().
  • 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) and new String("hi") (rarely needed).
  • βœ… Join Strings with + (concatenation). Once text joins in, numbers become text too, read left to right.
  • βœ… length() counts characters, and charAt(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. 1

    How do you write a String value in Java?

    Why: Strings use double quotes; single quotes are for a single char.

  2. 2

    What does it mean that a String is immutable?

    Why: An immutable String never changes; operations build a new String instead.

  3. 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. 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.

Java String Pool

Share & Connect