On W3Schools, “Java string functions” refers mainly to methods of Java’s String class, such as length(), toUpperCase(), indexOf(), and replace(). These methods let you inspect, search, compare, and transform text; because Java strings are immutable, methods that appear to change a string return a new string instead.
What “string functions” means in Java
Java calls operations attached to an object methods, rather than usually calling them functions. A string is an object of the built-in String class, and its methods are called with dot notation. For example, message.length() asks the string stored in message for its length. W3Schools’ Java string material introduces this style through practical examples and a reference to common methods.
A typical declaration and method call look like this:
String message = "Hello Java";
int count = message.length();
String upper = message.toUpperCase();
Here, count is 10, while upper is "HELLO JAVA". The parentheses are important: length() is a method call, not a field access. This differs from arrays, whose size is read with the length field and no parentheses.
Creating strings and understanding immutability
Most Java code creates a string literal by placing text in double quotation marks, then stores it in a variable declared with String. You can also create strings from other values with methods such as String.valueOf(). A string literal is not modified in place when a method is called. Instead, a method that transforms text gives back a result, and you can store that result in a new variable or assign it back to the original variable.
String name = "Mina";
name.toUpperCase();
System.out.println(name);
This prints Mina, not MINA, because the returned uppercase string was ignored. To keep the transformed value, write name = name.toUpperCase(); or assign it to another variable. This behavior is called immutability: the characters in a String object cannot be changed after that object has been created. Immutability helps make strings predictable when they are shared, but it can surprise beginners who expect an operation to edit the original value.
Everyday methods for length and letter case
Several methods are useful for basic inspection and formatting. Method calls are case-sensitive: toLowerCase() is valid, while a differently capitalized method name is not.
length()returns the number of UTF-16 code units in the string as an integer. For ordinary English text, this usually matches the number of visible characters.toUpperCase()returns a string with letters converted to uppercase, andtoLowerCase()returns one with letters converted to lowercase.isEmpty()returnstrueonly when the string has zero length.isBlank(), available since Java 11, returnstruewhen the string is empty or contains only whitespace characters as defined by Java.
For example, "Java".length() returns 4, and "Java".toLowerCase() returns "java". Uppercase and lowercase conversion can depend on language rules. If a program needs stable, locale-independent case handling—for example, when normalizing identifiers—use the overload that accepts a locale, often Locale.ROOT, rather than assuming every language follows English casing conventions.
Searching strings and checking for text
Search methods help locate a character or determine whether a string contains a piece of text. indexOf() returns the index of the first matching character or substring. Java indexes start at zero, so the first character is at index 0. If no match exists, indexOf() returns -1.
String sentence = "Java makes text handling practical";
int position = sentence.indexOf("text");
boolean hasJava = sentence.contains("Java");
In this example, position is 11, and hasJava is true. The contains() method returns a boolean and is convenient when the location is not needed. Related methods include lastIndexOf(), which finds the last occurrence, and startsWith() and endsWith(), which test the beginning and end of a string.
These searches are case-sensitive. For example, "Java".contains("java") is false. If a case-insensitive search is required, decide how to normalize both values and consider locale rules; do not assume contains() ignores case. Always handle a possible -1 result before using a search position in another operation.
Extracting, replacing, and joining text
substring() extracts part of a string. Its one-argument form starts at the given index and continues to the end. Its two-argument form uses a start index and an end index, with the end index excluded. Thus "notebook".substring(0, 4) returns "note". The indexes must be within the allowed range, or Java throws a StringIndexOutOfBoundsException.
replace() returns a string with matching characters or character sequences replaced. For instance, "red fox".replace("red", "blue") produces "blue fox". It does not change the original string. A common related method, replaceAll(), treats its first argument as a regular expression, not ordinary literal text. Use replace() when you want a literal match; choose replaceAll() only when regex behavior is intended.
For simple joining, the + operator combines strings and values that Java can convert to text. The concat() method joins one string to another, but + is often easier to read when combining several pieces. For many additions inside a loop, repeatedly creating new strings can be inefficient; use StringBuilder to build the result and call toString() when finished.
Comparing strings correctly
One of the most important Java string rules is to compare text with equals(), not usually with ==. The equals() method checks whether two strings contain the same sequence of characters. By contrast, == checks whether two references point to the very same object. Two separately created strings can have identical text while being different objects.
String first = new String("cat");
String second = new String("cat");
boolean sameText = first.equals(second);
boolean sameObject = first == second;
Here, sameText is true, while sameObject is false. The equalsIgnoreCase() method compares text without distinguishing uppercase from lowercase, which is useful for simple case-insensitive checks. It does not perform sophisticated language-aware sorting or matching. For ordering strings alphabetically according to their character values, use compareTo(); it returns a negative number, zero, or a positive number rather than a simple true-or-false result.
When a string might be null, calling a method directly on it causes a NullPointerException. A null-safe comparison can put the known, non-null literal first, as in "yes".equals(answer). This returns false if answer is null. It is also important to distinguish null from an empty string: null means there is no string object, while "" is a real string with length zero.
Whitespace, splitting, and converting values
Whitespace handling depends on what kind of whitespace you mean. trim() removes leading and trailing characters whose values are at or below the traditional ASCII space range. Since Java 11, strip(), stripLeading(), and stripTrailing() provide Unicode-aware whitespace stripping. Neither trim() nor strip() removes spaces from the middle of a string. For example, trimming " blue sky " gives "blue sky", not "bluesky".
The split() method separates a string using a regular-expression delimiter and returns an array of strings. To split comma-separated text, a simple comma delimiter works when the data has no quoted commas or other CSV rules. To split on a character that has special meaning in regular expressions, escape it appropriately. A period, for example, means “any character” in a regular expression, so splitting on a literal period requires an escaped pattern such as "\." in Java source. For real CSV files, use a CSV parser rather than treating every comma as a simple separator.
To turn a number or another value into text, use String.valueOf(value). This makes the conversion explicit and supports several primitive types and objects. Be aware that converting a null object reference with String.valueOf() produces the text "null"; it does not preserve a null reference. That distinction matters when displaying or validating data.
Common mistakes and practical choices
Many errors come from mixing up a method’s return value, its index rules, or its assumptions about the input. Before using a string method in application logic, check the following:
- Store the result of a transformation if you need the changed text; methods such as
replace()do not edit the original string. - Check for
-1afterindexOf()before using the result as an index. - Remember that
substring(begin, end)excludesend, and confirm the indexes are in range. - Use
equals()for matching text; reserve==for checking reference identity. - Choose
isEmpty()when only zero length matters, andisBlank()when whitespace-only strings should also count as blank. The latter requires Java 11 or later. - Use
replace()for literal replacement andreplaceAll()for regular-expression replacement.
Method choice is about intent. If the question is “does this text include a word?”, contains() communicates that clearly. If a position is needed, use indexOf(). If the goal is to compare two values regardless of capitalization, choose equalsIgnoreCase() while keeping language and locale requirements in mind. Clear intent makes code easier to review and reduces boundary errors.
Frequently Asked Questions
What are string functions in Java?
They are commonly called String methods: operations such as length(), contains(), substring(), and replace() that inspect or return text values.
Does Java have a string length function?
Use the length() method, written with parentheses: text.length(). It returns an integer. This differs from an array, which uses the length field without parentheses.
How do I compare two strings in Java?
Use first.equals(second) to compare their text. Use equalsIgnoreCase() if a basic comparison should ignore letter case. Avoid == for ordinary text comparison because it checks object identity.
Why does toUpperCase() not change my string?
Java strings are immutable, so toUpperCase() returns a new string. Assign the result, for example text = text.toUpperCase();, if you want the variable to refer to the uppercase value.
What is the difference between replace() and replaceAll()?replace() replaces literal characters or character sequences. replaceAll() interprets its search argument as a regular expression, so special regex characters may need escaping.
Which Java string methods are available in older versions?
Core methods such as length(), equals(), indexOf(), and substring() have long been part of Java. Methods including isBlank() and strip() were added in Java 11, so check the project’s Java version before using them.
Related
- Balance of Payments Notes: Accounts, Examples and Meaning
- Java split(): How It Handles Delimiters and Limits
- Java String split(): Syntax, Regex, and Examples
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Power Query Find Text in a String: M Functions and ExamplesTo find whether a Power Query text value contains a word or phrase, use Text.Contains. In a Custom…
- PySpark String Functions: Examples and Common UsesPySpark string functions are built-in column operations in pyspark.sql.functions for cleaning, transforming, searching, and parsing text in a…
- Excel Formula for Checking Account RegisterThe core formula for a checking account register in Excel is a running balance: =SUM($C$2:C2) (or =C2 for…
- JavaScript String match(): How It Works and When to Use ItJavaScript’s String.prototype.match() method searches a string using a regular expression and returns information about the match, or null…
- Excel Formula Opposite of CONCATENATE: Split Text ApartThe closest Excel formula to the opposite of CONCATENATE is =TEXTSPLIT(A2,"|"): it takes text in A2 and splits…
- Remove Formula in Excel but Keep Data as Values SafelyTo remove formulas in Excel but keep the data they currently display, select the formula cells, copy them,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.