Web Analytics

Java Strings

Beginner ~30 min read

In Java, a String is not a primitive type like int or char. It is an Object that represents a sequence of characters. Because handling text is so common, Java treats Strings specially, giving them their own memory area called the "String Constant Pool."

Creating Strings

There are two ways to create a String object:

  1. String Literal: String s = "Hello"; (Stored in String Pool)
  2. new Keyword: String s = new String("Hello"); (Stored in Heap)
Best Practice: Always use String literals (String s = "Hello"). It allows Java to optimize memory by reusing identical strings from the pool.

String Immutability

Strings in Java are immutable (unchangeable). Once a String object is created, its data cannot be changed. If you try to modify it, Java creates a new String object instead.

Java String Pool and Immutability Diagram
Output
Click Run to execute your code

Comparing Strings

Comparing strings can be tricky because they are objects.

  • == compares references (memory address). Are they the exact same object?
  • .equals() compares content (values). Do they have the same characters?
Common Mistake: Never compare strings with == unless you specifically check for identity. Always use str1.equals(str2) to check if the text is the same.

Common String Methods

The String class provides many useful methods for text manipulation.

Output
Click Run to execute your code

Summary

  • String is an object, not a primitive type.
  • Strings are immutable; they cannot be changed once created.
  • String literals are stored in the String Constant Pool for memory efficiency.
  • Always use .equals() to compare String content, not ==.

What's Next?

Strings allow us to store a sequence of characters. But what if we want to store a sequence of numbers, or names, or any other data type? That's where Arrays come in. Let's learn about them next.