1. Introduction to Strings in Java
A String is used to store text in Java, such as a product name, customer email, order status, or city in an address. Almost every practical Java program works with strings.
Premium Video
This video is available to Premium members or users who have purchased the course.
Sign in to UnlockA String is an object of the class java.lang.String. Unlike int and double, it is not a primitive data type. A String variable holds a reference to a String object.
Java automatically makes classes in java.lang available, so you do not need to write import java.lang.String;.
Learning objectives
After reading this article, you will be able to:
- Understand what a String is in Java.
- Create strings using literals and the
Stringconstructor. - Use
length()andcharAt(). - Check strings with
isEmpty()andisBlank(). - Join text using
+. - Convert between
Stringandchar[]. - Convert values using
String.valueOf()andtoString(). - Handle
nullsafely.
2. What Is a String?
A String is an object that represents a sequence of characters. Characters are ordered, and indexing starts at 0.
For example, in "Wireless":
| Index | Character |
|---|---|
| 0 | W |
| 1 | i |
| 2 | r |
| 3 | e |
| 4 | l |
| 5 | e |
| 6 | s |
| 7 | s |
Complete runnable example
Expected output
Product: Wireless MouseClass: java.lang.String
The getClass().getName() expression returns the fully qualified class name. The result confirms that productName refers to a java.lang.String object.
Java represents strings using UTF-16 code units. Most common English letters and digits occupy one code unit, while some Unicode characters, including certain emoji, require two code units. For that reason, length() counts UTF-16 code units rather than always counting user-perceived characters.
Since Java 9, the JVM may use a compact byte-based representation for strings whose characters fit Latin-1. This is an implementation detail; you normally do not need to manage it yourself.
3. Two Ways to Create a String
Java commonly creates strings using string literals or the String constructor.
3.1 Using a string literal
A string literal is text enclosed in double quotation marks:
3.2 Using the new String() constructor
You can also write:
This explicitly creates a new String object.
Complete runnable example
Expected output
Laptop Stand
Laptop Stand
true
false
Both variables contain the same text, so equals() returns true. The literal and the explicitly created object are different references in this example, so == returns false.
What is the String pool?
Java maintains a shared pool of string literals. Repeated occurrences of the same literal can reuse the pooled String object. By contrast, new String("Laptop Stand") explicitly creates a fresh String object.
Best practice: Prefer string literals for ordinary strings. They are concise and allow Java to reuse pooled instances.
4. The length() Method
The length() method returns the number of UTF-16 code units in a String.
Complete runnable example
Expected output
Text: ShippedLength: 7
String length vs. array length
| Type | Syntax | Meaning |
|---|---|---|
| Array | numbers.length | The array's size |
| String | text.length() | Number of UTF-16 code units |
Notice the syntax difference: an array uses the length field without parentheses, while a String uses the length() method.
5. The charAt() Method
The charAt(index) method returns the character at the specified index. Because indexing begins at zero, the first character is at index 0, and the last character is at length() - 1.
Complete runnable example
Expected output
S
p
d
An index outside the valid range causes a StringIndexOutOfBoundsException. For "Shipped", valid indexes are 0 through 6; index 7 is beyond the end.
Traversing every character
Expected output
J
a
v
a
This pattern—a loop, an index, and a charAt() call—is a common starting point for string-processing algorithms.
6. isEmpty() and isBlank()
Both methods check whether a String contains content, but they have different meanings.
isEmpty()returnstrueonly when the String has zero characters.isBlank()returnstruewhen the String is empty or consists entirely of whitespace characters. It was introduced in Java 11.
Complete runnable example
Expected output
true
false
true
false
Comparison table
| Input | isEmpty() | isBlank() |
|---|---|---|
"" | true | true |
" " | false | true |
"\t\n" | false | true |
"a" | false | false |
" hello " | false | false |
Use isEmpty() when you only need to check for zero characters. Use isBlank() when whitespace-only input should count as empty, such as a search box or review field.
Java version note: isBlank() requires Java 11 or later. Neither method can be called safely on a null reference without checking for null first.
7. String Concatenation Using +
The + operator joins strings. Java evaluates concatenation from left to right, and when one operand is a String, other values can be converted to text and joined.
Complete runnable example
Expected output
Alice KhanJoining strings with other data types
Expected output
Product: keyboard
Price: 2500
Available: true
A common concatenation mistake
Consider these expressions:
The first expression produces "Total items: 23" because the text concatenation happens before the final + 3. In the second expression, parentheses force 2 + 3 to be calculated first.
Complete runnable example
Expected output
Total items: 23Total items: 5
Use parentheses around arithmetic when mixing numeric calculations with strings.
For a few short concatenations, + is convenient. When repeatedly building long text inside a loop, consider StringBuilder to avoid creating many intermediate String objects.
8. Converting a String to char[]
The toCharArray() method copies a String's characters into a new character array. The resulting array is independent of the original String.
Complete runnable example
Expected output
String: CART
Array: [P, A, R, T]
Changing letters[0] does not change word, because Strings are immutable and toCharArray() creates a separate array.
9. Converting char[] to a String
Use the String constructor that accepts a character array to create a String from its contents.
Complete runnable example
Expected output
String: CART
First array character: P
The constructor copies the character data into the String. Changing the original array later does not change the String.
Both toCharArray() and new String(char[]) involve copying character data and take time proportional to the length of the text, or O(n).
10. String.valueOf() and toString()
Java often needs to convert numbers, booleans, and objects into text. Two common tools are the static String.valueOf() method and the instance method toString().
Using String.valueOf()
String.valueOf() has overloads for primitive types and object references.
Complete runnable example
Expected output
29.99
42true
Understanding toString()
All Java classes inherit toString() from Object. Classes can override it to provide a useful text representation. The String class's toString() method returns the String itself.
For a non-null object, String.valueOf(value) and value.toString() usually produce the same text. Their behavior differs when the reference is null.
| Expression | Behavior when the reference is null |
|---|---|
String.valueOf(value) | Returns the text "null" |
value.toString() | Throws NullPointerException |
"" + value | Produces the text "null" |
Complete runnable example
Expected output
null
null
When a value might be null, String.valueOf() is a clear way to convert it to text without throwing an exception.
11. Strings Can Be null
A String variable is a reference. It can refer to a String object, or it can be null, meaning it does not currently refer to an object.
Calling a method on a null reference causes a NullPointerException (NPE).
Unsafe example
This throws a NullPointerException, because there is no String object on which to call length().
Safely checking for null
Expected output
Coupon code is not provided.The same null check is needed before calling isEmpty() or isBlank().
A null-safe constant comparison
If you want to compare a value to a known literal, placing the literal first avoids calling a method on a possibly null reference:
Expected output
falseBy contrast, couponCode.equals("WELCOME10") would throw a NullPointerException when couponCode is null.
An empty string ("") and null are not the same. An empty string is a real String object with length zero; null means there is no referenced String object.
12. Common String Mistakes
Mistake 1: Using == to compare String content
== compares references, while equals() compares String content.
Output:
falsetrue
Mistake 2: Using array syntax for String length
Incorrect: text.length
Correct: text.length()
Arrays use the length field, but Strings use the length() method.
Mistake 3: Accessing an invalid character index
For a String of length n, valid indexes are 0 through n - 1. Invalid indexes cause StringIndexOutOfBoundsException.
Mistake 4: Treating whitespace as an empty String
" ".isEmpty() is false, while " ".isBlank() is true in Java 11 and later.
Mistake 5: Calling methods on null
Check whether the reference is null before calling length(), isEmpty(), isBlank(), or equals() on it.
Mistake 6: Forgetting arithmetic precedence in concatenation
Use parentheses around arithmetic when you want addition to happen before joining with a String.
13. Time Complexity and Best Practices
| Operation | Typical time complexity | Reason |
|---|---|---|
length() | O(1) | Length is available directly |
charAt(index) | O(1) | Retrieves a character at an index |
toCharArray() | O(n) | Copies the characters |
new String(charArray) | O(n) | Copies character data |
| String concatenation | Depends on total text length | Creates a resulting String and may create intermediate strings |
Best practices
- Prefer String literals for ordinary text.
- Use
equals()to compare String contents. - Remember that Strings are immutable.
- Use
length()with parentheses. - Use
isBlank()when whitespace-only input should count as blank; it requires Java 11 or later. - Check for
nullbefore calling instance methods. - Put parentheses around arithmetic in concatenation expressions when needed.
- Use
StringBuilderfor repeated text building in loops. - Remember that String indexes refer to UTF-16 code units, not always user-perceived characters.
14. Practice Questions with Answers
Question 1: Is String a primitive data type in Java?
Answer: No. String is a class in java.lang.
Question 2: What is the difference between length and length()?
Answer: Arrays use the length field, while Strings use the length() method.
Question 3: What does charAt(0) return?
Answer: It returns the first UTF-16 code unit as a char, if the String is not empty.
Question 4: What is the difference between isEmpty() and isBlank()?
Answer: isEmpty() checks whether length is zero. isBlank() also returns true for strings containing only whitespace and requires Java 11 or later.
Question 5: What is printed?
Answer:
4a
Question 6: What is printed?
Answer:
Total: 23Total: 5
Question 7: Why is String.valueOf(value) useful when value may be null?
Answer: It returns the text "null" instead of throwing a NullPointerException.
Question 8: Write a program to print each character of a String on a separate line.
Answer:
Expected output
c
o
d
e
15. Frequently Asked Questions (FAQs)
1. What is a String in Java?
A String is an object that represents a sequence of characters.
2. Does Java automatically import String?
Yes. String belongs to java.lang, which is automatically available.
3. Are Strings mutable?
No. Strings are immutable: once a String object is created, its contents cannot be changed.
4. What is the difference between == and equals() for Strings?
== checks whether references point to the same object. equals() checks whether the String contents are equal.
5. Is isBlank() available in Java 8?
No. isBlank() was added in Java 11. In Java 8, a different check is needed if whitespace-only text should count as blank.
6. What happens if charAt() receives an invalid index?
It throws StringIndexOutOfBoundsException.
7. Can a String variable be null?
Yes. A String variable is a reference and can hold null. Calling an instance method on it causes NullPointerException.
8. Why use StringBuilder?
It is useful when building text repeatedly, especially in loops, because it avoids creating a new intermediate String for every concatenation step.
16. Quick Revision
Stringis an object type injava.lang, not a primitive.- String literals are usually preferred over
new String(...). length()returns the number of UTF-16 code units.charAt(index)returns the character at a valid index.isEmpty()checks for zero characters.isBlank()also treats whitespace-only text as blank and requires Java 11 or later.- The
+operator concatenates strings and can convert other values to text. - Use parentheses when arithmetic must happen before concatenation.
toCharArray()copies characters into a new array.String.valueOf()converts values to text and handles null references by returning"null".- Check for null before calling instance methods.
- Use
equals()for String content comparison.
17. Conclusion
Strings are fundamental to Java because they represent names, messages, statuses, and nearly every other kind of text. Learn how to create them, measure their length, access characters, check for blank input, concatenate values, and convert between strings and character arrays. Above all, remember that Strings are immutable, == is not a content comparison, and null references must be handled before calling instance methods. These basics provide a strong foundation for more advanced Java string processing.