Java’s basic string functions are methods on the String class for measuring, searching, comparing, extracting, changing, and formatting text. For example, call text.length() to get its length, text.contains("Java") to search it, and text.substring(0, 4) to extract part of it; remember that strings are immutable, so methods that appear to change text return a new string.
What a Java string is
A Java string is an object of the String class, usually written as a string literal in double quotes, such as "Hello". You can assign it to a variable with String message = "Hello";. The class provides many methods for common text operations, so most programs do not need to process strings one character at a time.
Strings are immutable: after a String object is created, its contents cannot be changed. A method such as toUpperCase() does not alter the existing object. It returns a string containing the uppercase result. To keep that result, assign it:
String name = "Mina";
name.toUpperCase(); // The returned value is not saved.
name = name.toUpperCase(); // name now refers to "MINA".
Immutability makes strings predictable to share and pass between methods, but it can surprise new programmers who expect a method call to update a variable automatically. For repeated construction of text inside a loop, StringBuilder is usually a better fit than repeatedly combining strings.
Length, characters, and empty strings
length() returns the number of UTF-16 code units in a string, and an empty string, "", has length zero. The method is called with parentheses because it is a method, not a field. To read the character at a position, use charAt(index); positions start at zero, so the first character is at index 0, and the last is at length() - 1.
String word = "Java";
int size = word.length(); // 4
char first = word.charAt(0); // 'J'
char last = word.charAt(size - 1); // 'a'
An index outside the valid range causes a StringIndexOutOfBoundsException. Check the length before accessing a position if the string might be empty or the index comes from user input.
There is an important Unicode detail: length() counts UTF-16 code units, not necessarily the number of characters a person sees. Many common letters use one code unit, but some symbols, including many emoji, use a pair. For code-point-aware processing, use methods such as codePointCount() or codePoints() rather than assuming each visible symbol corresponds to one char.
Comparing strings correctly
Use equals() to test whether two strings contain the same sequence of characters. The == operator instead tests whether two references point to the same object. It can appear to work with string literals because Java may reuse literal objects, but it is not a reliable way to compare text.
String input = new String("yes");
boolean sameText = input.equals("yes"); // true
boolean sameObject = input == "yes"; // not a text comparison
For case-insensitive comparison, use equalsIgnoreCase(). For ordering, compareTo() compares strings lexicographically and returns a negative number, zero, or a positive number depending on their relative order. Do not assume it returns exactly -1 or 1. Case conversion and case-insensitive comparison can be affected by language rules; when comparing identifiers that should follow a consistent convention, consider using toLowerCase(Locale.ROOT) or toUpperCase(Locale.ROOT).
A possible null value needs special care. Calling input.equals("yes") throws a NullPointerException if input is null. If null is possible, check it first, or put a known non-null literal first: "yes".equals(input).
Finding text and checking prefixes
Use contains(sequence) to check whether a string includes a particular sequence of characters. Related methods answer more specific questions: startsWith(prefix) checks the beginning, and endsWith(suffix) checks the end. These methods return boolean values and are useful for simple validation or filtering.
String file = "report.csv";
boolean isCsv = file.endsWith(".csv"); // true
boolean hasPortion = file.contains("port"); // true
boolean startsWithReport = file.startsWith("report"); // true
For the position of a match, use indexOf(). It returns the index of the first match, or -1 if there is no match. Overloads let you search for a character or string, optionally beginning at a specified position. Use lastIndexOf() when the final occurrence is what matters. Since zero is a valid position, test for -1 explicitly rather than treating the result as a simple true-or-false value.
Extracting and joining text
substring(beginIndex) returns the portion from the given index through the end. substring(beginIndex, endIndex) returns the portion from the first index up to, but not including, the second. That end-exclusive convention is common in Java and makes the length of the result equal to endIndex - beginIndex.
String language = "Java programming";
String firstWord = language.substring(0, 4); // "Java"
String rest = language.substring(5); // "programming"
Both indexes must be within the permitted bounds, and the beginning cannot be greater than the end. Invalid values cause an index exception. If the text might not have the expected structure, check its length or locate a delimiter before extracting a portion.
For simple combination, the + operator and concat() are available. In everyday code, + is often the clearest choice, especially for a small number of values. When combining many pieces repeatedly, such as in a loop, use StringBuilder and append each piece; because strings are immutable, repeated concatenation can create many intermediate string objects.
Replacing text and changing case
replace(old, replacement) replaces literal character sequences; it does not interpret the search text as a regular expression. For example, "a.b".replace(".", "-") replaces the period character. By contrast, replaceAll(regex, replacement) treats its first argument as a regular expression, and replaceFirst(regex, replacement) changes only the first match.
This distinction matters because punctuation can have special meaning in regular expressions. A period in a regex means “any character,” so to match a literal period with replaceAll(), escape it appropriately, such as "\\." in a Java string literal. For straightforward literal replacement, prefer replace() to avoid unnecessary regex rules.
toLowerCase() and toUpperCase() return strings with case converted according to a locale. They do not modify the original string, and case conversion is not always a one-character-for-one-character operation across all writing systems. Use them for display or carefully defined normalization, not as a substitute for a complete language-aware text comparison.
Splitting, trimming, and blank text
split(regex) divides a string around matches of a regular expression and returns an array. Because its argument is a regex, a delimiter such as a period may need escaping. For a comma-separated line, line.split(",") is straightforward. The one-argument form discards trailing empty strings; use split(",", -1) when trailing empty fields must be preserved. Splitting on commas is not enough to parse full CSV files, which can include quoted fields and embedded commas; use a CSV parser for that format.
trim() removes leading and trailing characters at or below the traditional ASCII space range. In Java 11 and later, strip() and stripLeading() or stripTrailing() provide Unicode-aware whitespace handling. Neither trim() nor strip() removes spaces between words. Java 11 also added isBlank(), which returns true for an empty string or one containing only whitespace as defined by the method.
These methods are not interchangeable: isEmpty() is true only when the length is zero, while isBlank() also accepts whitespace-only text. For example, " " is not empty but is blank. Choose according to whether whitespace should count as meaningful input.
Formatting strings and choosing an approach
For readable text assembled from values, String.format() uses format specifiers. For example, String.format("Name: %s, score: %d", name, score) inserts a string and an integer into the marked positions. Specifiers must match the supplied values; a mismatch can cause a formatting exception. Formatting is useful for reports and fixed layouts, while concatenation is often simpler for a short message.
Choose a method based on the exact operation rather than using a broad tool for everything:
- Use
equals()for exact text equality andcontains()for a simple presence check. - Use
replace()for literal replacement and regex methods only when a pattern is required. - Use
substring()for known positions, but validate indexes when input is uncertain. - Use
split()for simple delimiters; use a format-specific parser for structured data such as CSV. - Use
StringBuilderfor repeated construction, and ordinary string operations for most small, simple expressions.
Common mistakes and practical safeguards
A frequent mistake is calling a string method and ignoring its return value. Since strings are immutable, write text = text.strip() if the cleaned version should replace the variable. Another common error is using == instead of equals(), or forgetting that indexes begin at zero and substring end positions are excluded.
Also consider nulls and untrusted input. A method call on a null reference fails, and an unexpectedly long string can consume memory or processing time if a program repeatedly transforms it. Validate input length and structure where appropriate. Avoid assuming a user-entered string has a fixed number of characters, and do not use a basic string split as a complete parser for a more complex data format.
Frequently Asked Questions
How do I compare two strings in Java?
Use equals() for exact content equality and equalsIgnoreCase() for a case-insensitive comparison. Use == only when you intentionally need to compare object references.
Does a Java string change when I call replace or toUpperCase?
No. A String is immutable, and these methods return a new string. Assign the returned value if you want to keep it.
What is the difference between isEmpty() and isBlank()?isEmpty() checks whether the string has zero length. isBlank(), available since Java 11, also returns true when the string consists only of whitespace.
How do I get one character from a string?
Call charAt(index), using a zero-based index, and ensure it is less than length(). Remember that a char is a UTF-16 code unit, so some visible Unicode symbols take two positions.
When should I use StringBuilder instead of String?
Use StringBuilder when repeatedly appending or modifying text, especially in a loop. For a few values or ordinary text operations, a regular String and the + operator are usually clearer.
Related
- Arduino String replace(): Syntax, Examples, and Tips
- Split a Cell in Google Sheets: What Actually Works
- SOLIDWORKS Split Tool: How to Split and Save Bodies
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Formula Between Two Numbers: ExamplesTo check whether a value in A2 is between a lower limit in B2 and an upper limit…
- Tableau NOT IN Function: Syntax, Use & FixesThe short answer: Tableau does not have a dedicated NOT IN function. You achieve the same logic by…
- COUNTIF Not Duplicate in Excel: Count Unique ValuesTo count values that appear only once in Excel, use =SUMPRODUCT((A2:A10<>"")*(COUNTIF(A2:A10,A2:A10)=1)) when the values are in A2:A10; it…
- Filter Duplicate Data in Excel: Find or Remove RowsTo filter duplicate records in Excel, add a helper column with a COUNTIF formula, then filter that column…
- Excel Slicer Custom Sort: Control the Order of ItemsTo custom-sort an Excel slicer, create or use an Excel custom list for the item labels, then open…
- Excel Column Minus Column Formula: Examples and FixesIf your values are in A2:A100 and B2:B100, enter =A2-B2 in C2 to subtract the value in column…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.