What Does String Do in Java? A Clear Guide

How-to basics · Updated November 23, 2026

In Java, a String is an object that represents a sequence of characters, and its primary job is to store and manipulate text. It is not a primitive type like int or boolean, but a class in the java.lang package, and every string literal you write (like “hello”) is automatically converted into a String object. Beyond just holding text, the String class provides dozens of built-in methods for searching, comparing, extracting, and transforming that text, making it the most commonly used class in Java programming.

Background: Why Strings Are Special

Strings are so fundamental that Java treats them with special syntax and rules. You can create a string with double quotes without using the new keyword, which is a shortcut not available for other objects. For example:

String greeting = "Hello"; // literal
String another = new String("Hello"); // explicit object

Both lines create a String object, but the first is more common and efficient. Java also makes strings immutable—once you create a string, you cannot change its characters. Any operation that seems to modify a string (like toUpperCase()) actually returns a brand-new string, leaving the original untouched. This immutability is a deliberate design choice: it makes strings thread-safe, allows them to be safely shared, and enables caching for performance.

How Strings Work Internally

In modern Java (version 9 and later), a String stores its characters in a byte[] array, along with a flag that indicates the encoding (either LATIN-1 or UTF-16). Earlier versions used a char[] array. The internal structure is hidden from you, but it means that each character takes either 1 or 2 bytes depending on its content. This optimization reduces memory usage for strings that only contain ASCII characters.

When you concatenate strings with the + operator, the Java compiler often converts the operation into a StringBuilder or StringBuffer behind the scenes. For example, String s = "a" + "b" is compiled to something like new StringBuilder().append("a").append("b").toString(). This avoids creating intermediate string objects, but if you do concatenation in a loop, the compiler may still create multiple builders, which is why manual use of StringBuilder is recommended for heavy text building.

Common Operations and Examples

The String class offers a rich API. Here are the most frequently used methods with simple examples:

  • Length: "hello".length() returns 5.
  • Character access: "hello".charAt(1) returns 'e'.
  • Substring: "hello".substring(1, 3) returns "el" (end index exclusive).
  • Comparison: "hello".equals("hello") returns true; use equalsIgnoreCase to ignore case.
  • Search: "hello".indexOf('l') returns 2 (first occurrence).
  • Replace: "hello".replace('l', 'p') returns "heppo".
  • Split: "a,b,c".split(",") returns an array ["a", "b", "c"].
  • Trim: " hi ".trim() returns "hi" (removes leading/trailing spaces).

Note that methods like toLowerCase() and toUpperCase() are locale-sensitive, so if you need consistent results across languages, use the overload that accepts a Locale.

How to Choose: String vs StringBuilder vs StringBuffer

When you need to build or modify text repeatedly, using String directly is inefficient because each modification creates a new object. Instead, Java provides two mutable alternatives:

  • StringBuilder – not thread-safe, but faster. Use it in single-threaded code or inside a method.
  • StringBuffer – thread-safe (methods are synchronized), but slightly slower. Use it only if multiple threads access the same instance.

As a rule of thumb: if you are concatenating fewer than, say, 5 strings, the + operator is fine. For loops or large text assembly, use StringBuilder. For example:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
    sb.append("line " + i + "\n");
}
String result = sb.toString();

This is much more memory-efficient than doing result += "line " + i in a loop, which would create thousands of intermediate strings.

Common Problems and Misconceptions

One of the biggest pitfalls is comparing strings with == instead of .equals(). The == operator checks if two references point to the same object, not if the content is equal. For example:

String a = "hello";
String b = "hello";
String c = new String("hello");
System.out.println(a == b); // true (due to interning)
System.out.println(a == c); // false (different objects)
System.out.println(a.equals(c)); // true (content equal)

Because of string interning (where identical literals are reused), a == b may be true, but this is unreliable for strings created at runtime. Always use .equals() for content comparison.

Another issue is that strings are immutable, so if you need to modify a string in place (like changing a character), you must convert it to a char[] or use StringBuilder. For example:

String s = "hello";
char[] chars = s.toCharArray();
chars[0] = 'j';
String newS = new String(chars); // "jello"

Also, be aware that substring() in Java 7 and later copies the underlying array, so it does not keep a reference to the original string (which was a memory leak issue in Java 6 and earlier).

Performance and Memory Considerations

Strings can consume significant memory, especially in large applications. Each string object has overhead (object header, array reference, hash field, etc.), so storing many small strings can be wasteful. To reduce memory, consider:

  • Using String.intern() to reuse canonical representations, but be careful—interned strings are stored in the heap’s string pool and are not garbage collected until the JVM exits, so overuse can cause memory leaks.
  • Using StringBuilder for building, then converting to a single string.
  • Using char[] or byte[] directly if you only need to read characters and don’t need string methods.

For very large text processing, consider java.io.Reader and Writer classes to stream data instead of loading everything into a string.

Alternatives to String

While String is the standard for text, Java offers other types for specific needs:

  • char[] – mutable, but lacks methods; useful for security-sensitive data like passwords, because you can clear the array after use (strings cannot be wiped).
  • StringBuilder/StringBuffer – for building strings efficiently.
  • java.util.regex.Pattern – for complex pattern matching, not a text container but works with strings.
  • Java 15+ Text Blocks – multi-line strings using triple quotes, which make HTML, JSON, or SQL easier to write.

For example, a text block:

String json = """
{
  "name": "John",
  "age": 30
}
""";

This is not a different class—it’s just a string literal with newlines preserved.

Frequently Asked Questions

Is String a primitive type in Java? No, it’s a class in java.lang. However, it has special language support (literals, + operator) that makes it feel primitive.

Why are strings immutable? Immutability provides security (strings are often used for file paths, class names), thread safety (multiple threads can share a string without synchronization), and performance (string pool caching). It also simplifies code reasoning.

What is the difference between == and .equals() for strings? == compares object references (memory addresses), while .equals() compares the actual character sequences. Always use .equals() to check if two strings have the same content.

How do I convert a string to an integer or double? Use Integer.parseInt(String) or Double.parseDouble(String). For example, int num = Integer.parseInt("123");. Be aware these throw NumberFormatException if the string is not a valid number.

Can I change a character in a string? No, because strings are immutable. You must create a new string, either by using substring() and concatenation, or by converting to a char[], modifying the array, and creating a new string.

What is string interning? The JVM maintains a pool of unique string literals. When you write a string literal, the JVM checks the pool and reuses the existing object if one with the same content exists. This saves memory but only applies to literals and strings explicitly interned via intern().

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.