In Java, String is the standard class for representing text, such as names, messages, and file paths. It is part of the java.lang package, so Java programs can use it without an import; Oracle’s Java documentation describes its behavior as part of the Java platform, not as a special Oracle-only feature.
What String means in Java
A string is an ordered sequence of characters treated as one value. For example, "Hello" is a string containing five letters. Java represents that value with the class String, whose name begins with a capital letter because it is a class. The type is used throughout Java APIs: methods read strings as input, return them as output, or use them as keys and labels.
For example, a variable can refer to a string like this:
String greeting = "Hello, Java";
The variable greeting refers to a String object. It is not a primitive type such as int or boolean. This distinction matters because strings have methods, can be null references, and follow object rules. Java does provide convenient literal syntax, so ordinary text does not require calling a constructor.
Background: String and Oracle Java
Oracle publishes Java development tools and documentation, but the Java language and platform are not simply a proprietary “Oracle string” system. The String class is part of Java’s standard library, in the java.lang package. It is available in Java implementations that provide the standard Java platform, including Oracle JDK and other compatible JDK distributions.
Because java.lang is automatically available, this works without an import statement:
String city = "Oslo";
By contrast, a class from another package—such as ArrayList from java.util—normally needs an import or a fully qualified name. Oracle’s online API documentation is useful for checking exact method behavior, but the same core String concepts apply across current Java implementations.
Creating strings: literals and constructors
The most common way to create a string is a string literal, written between double quotation marks. A literal can be assigned directly, passed to a method, or combined with other expressions:
String first = "Ada";
String message = "Hello, " + first;
Java also allows construction with new, but it is rarely necessary for ordinary text:
String a = "Java";
String b = new String("Java");
Both variables represent text with the same contents, but the expressions do not necessarily refer to the same object. A literal is normally drawn from the string pool, a shared area that allows identical interned literals to reuse objects. The explicit constructor creates a distinct object. This is one reason not to use == when the goal is to compare text.
For normal application code, prefer the literal or a value returned by an API. Creating extra String objects with new String(...) adds no benefit when only the text value is needed.
Immutability: why string operations return values
Java strings are immutable: after a String object is created, its character content cannot be changed. Methods that appear to modify a string instead return a result, often a new string. For example:
String word = "cat";
String upper = word.toUpperCase();
After these statements, word still refers to "cat", while upper refers to "CAT". If the result is not assigned or otherwise used, the original variable does not change:
word.toUpperCase(); // word is still "cat"
Immutability makes strings easier to share safely: code receiving a string cannot alter its contents behind the caller’s back. It also supports using strings as map keys, because their value does not change after insertion. The trade-off is that repeated edits can create many intermediate strings, so a mutable builder is often a better tool for constructing long text.
Comparing strings correctly
The most common string bug is comparing contents with ==. For object references, == checks whether both references point to the same object, not whether their text is equal. Use equals for an exact, case-sensitive content comparison:
String x = new String("Java");
String y = "Java";
boolean sameText = x.equals(y); // true
Calling equalsIgnoreCase compares text without considering letter case, which can suit some user-facing checks but is not a universal substitute for locale-aware text handling. For a safe comparison when a value might be null, either check for null first or call equals on a known non-null literal:
if ("admin".equals(role)) {
// handle the admin role
}
This form does not throw a NullPointerException if role is null. For sorting, compareTo provides lexicographic comparison, but its ordering is based on string character values and may not match a human language’s dictionary rules.
Useful String methods
The String API includes methods for inspecting, searching, and transforming text. Common examples include:
length()returns the number of UTF-16 code units in the string.isEmpty()checks whether the string has zero length; it does not treat spaces as empty.contains(sequence)checks whether a sequence of characters occurs within the string.startsWith(prefix)andendsWith(suffix)test the beginning and end.substring(beginIndex, endIndex)returns part of a string, using a starting index that is included and an ending index that is excluded.replace(old, replacement),toLowerCase(), andtrim()return transformed strings.
Indices are zero-based. For String text = "Java";, text.substring(1, 3) returns "av". An index outside the permitted range causes an IndexOutOfBoundsException, so code that calculates indices should check the string length or handle the exception appropriately.
For case conversion that is meant to follow a specific language’s rules, use the overload that accepts a Locale, rather than assuming the machine’s default locale is suitable. Similarly, trim() and strip() are not identical in their treatment of whitespace; consult the Java version’s API documentation when that distinction matters.
Characters, Unicode, and length
Java strings use UTF-16 encoding internally as specified by the Java API. This means a string’s length() counts UTF-16 code units, not necessarily the number of characters a person sees. Many common characters use one code unit, but some Unicode code points use a surrogate pair of two code units. A visible symbol can also consist of multiple code points—for example, a base letter followed by a combining accent.
Therefore, length() is suitable for many programming tasks, but it should not automatically be interpreted as a count of human-perceived characters. If code needs to iterate by Unicode code point, methods such as codePointAt and codePoints are available. More advanced text processing may need to account for grapheme clusters, which correspond more closely to what users perceive as individual characters.
Encoding is a separate issue from the Java String type. When reading or writing bytes—such as file contents or network data—choose an explicit character encoding, commonly UTF-8. A string itself is text in memory; conversion to bytes requires an encoding, and decoding bytes requires the matching choice to avoid corrupted text.
Building text efficiently
For a small number of values, the + operator is clear and convenient. Java compilers can optimize many concatenation expressions. For repeated concatenation inside a loop, however, creating a new immutable result on every iteration can do unnecessary work. Use StringBuilder when assembling text incrementally:
StringBuilder result = new StringBuilder();
for (String item : items) {
result.append(item).append(", ");
}
String joined = result.toString();
StringBuilder is mutable and is designed for building a string in a single thread. StringBuffer offers synchronized methods and is available for cases that need its synchronization behavior, though synchronization does not make every larger operation automatically thread-safe. For joining a collection with a delimiter, String.join can be more concise:
String names = String.join(", ", "Ada", "Lin", "Sam");
Choose the simplest approach that fits the task: concatenation for a short expression, StringBuilder for repeated appends, and a joining utility when combining values with separators.
Common mistakes and practical cautions
Several issues recur in Java string code, especially when input comes from users, files, or APIs:
- Using
==instead ofequalsfor value comparison can make a check depend on object identity or string-pool behavior. - Assuming an empty string and a null reference are the same is incorrect.
""is a valid string with zero length;nullmeans no object reference. - Assuming spaces make a string empty is also incorrect. Check or normalize whitespace deliberately if that is the requirement.
- Using
length()as a count of visible characters can produce surprising results with some Unicode text. - Building SQL by concatenating untrusted text can expose an application to SQL injection. Use prepared statements and parameter binding instead of treating string escaping as a reliable security boundary.
Also be careful when normalizing text for comparisons. Lowercasing may depend on locale, while trimming only removes certain whitespace at the ends and does not remove internal spaces. Define the exact comparison or cleanup rule that the application needs rather than applying transformations automatically.
Frequently Asked Questions
Is String a primitive type in Java?
No. String is a class, or reference type. Java gives string literals convenient syntax, but a string variable refers to an object rather than storing a primitive value such as an int.
Why is String capitalized in Java?String is the name of a Java class, and Java convention capitalizes class names. The lowercase word “string” is a general term for text, not the Java type name used in declarations.
What is the difference between String and StringBuilder?String is immutable, so its content cannot be changed. StringBuilder is mutable and is useful for building text through repeated appends; call toString() to obtain a final String.
Does String.length() count letters?
It counts UTF-16 code units. For ordinary basic Latin text that often matches the number of letters, but supplementary Unicode characters and combined symbols can require more careful code-point or grapheme-aware counting.
Should I use new String() in Java?
Usually not for ordinary text. A literal or a value returned by a method is simpler. new String(...) creates a separate object when one is specifically needed, but it does not make the text more valid or more permanent.
Is Java String the same in Oracle JDK and other JDKs?
The standard String API is part of the Java platform and is not exclusive to Oracle JDK. Internal implementation details can vary between Java versions or JDK vendors, so rely on documented behavior rather than assumptions about how strings are stored behind the scenes.
Related
- How to Split Data in Google Sheets
- SOLIDWORKS Split Part: Create Two Separate Bodies Guide
- How to Split an Object in SOLIDWORKS: Step-by-Step
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Merge Vertical Cells: Steps, Limits, and AlternativesTo merge cells vertically in Excel for Microsoft 365 on Windows, select a vertical range such as A2:A4,…
- Excel Text Usage Examples for Cleaning and FormattingExcel text examples often use TEXT to turn a number or date into a chosen display, such as…
- Will Google Sheets Get Power Query? What to Use InsteadNo—Google Sheets does not currently have a built-in version of Microsoft Power Query, and Google has not announced…
- Excel Freeze Pane Line: How to Remove ItTo get rid of a freeze pane line in Excel, select the affected worksheet, then choose View >…
- How to Delete a Locked Page in WordTo delete a page that Word will not let you edit, first check whether the document is protected:…
- How to Create a Color Key in Excel for Clearer DataTo create a color key in Excel, add a small legend beside or below your data, assign each…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.