Introduction to String Handling in Java
Course: Core Java Training
Topic: Introduction to String Handling in Java
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
Academy Website: JustAcademy
1. Introduction to String Handling
String handling in Java refers to creating, storing, accessing, comparing, searching, modifying, and processing sequences of characters. Strings are used in almost every Java application, including user input, names, addresses, messages, file paths, web requests, database records, and application logs.
Java provides the built-in String class in the java.lang package. Because this package is automatically available in Java programs, you generally do not need to import String explicitly.
Unlike a character array, a Java String is an object that represents a sequence of characters and is immutable. Immutability means that once a String object is created, its character sequence cannot be changed. Operations that appear to modify a string return a new string instead.
Why Is String Handling Important?
- To store and display text in applications.
- To validate user input, such as names, email addresses, and identifiers.
- To search for words or characters within text.
- To compare values and check whether strings match.
- To combine text with numbers and other data.
- To process text files, API responses, and database values.
- To format messages, reports, and application output.
2. What Is a String in Java?
A string is a sequence of characters represented by an object of the String class. Java strings can contain letters, digits, spaces, punctuation, and many Unicode characters.
Example
public class StringIntroduction {
public static void main(String[] args) {
String name = "Rahul";
String course = "Core Java";
String message = "Welcome to Java Programming!";
System.out.println(name);
System.out.println(course);
System.out.println(message);
}
}
Output:
Rahul
Core Java
Welcome to Java Programming!
Explanation:
String is the class used to represent text.
name, course, and message are reference variables.
- The text inside double quotation marks is a string literal.
System.out.println() displays the string in the console.
3. Declaring and Initializing Strings
A string variable can be declared first and assigned a value later, or it can be declared and initialized in one statement.
Declaration
String city;
This declares a local reference variable. It must be assigned a value before it is read.
Initialization
String city = "Mumbai";
This declares the variable and assigns it a reference to a String object.
Assigning a Value Later
public class StringAssignment {
public static void main(String[] args) {
String language;
language = "Java";
System.out.println(language);
}
}
Output:
Java
4. Creating Strings in Java
There are several ways to create strings. Two common approaches are using a string literal and using the new keyword.
4.1 Using a String Literal
String firstName = "Amit";
String secondName = "Priya";
String literals are commonly stored in the String pool, which allows identical literals to share a pooled String object when applicable.
4.2 Using the new Keyword
String name = new String("Amit");
This explicitly creates a new String object. The literal "Amit" may also refer to an object in the String pool. Using new String() is generally unnecessary for ordinary string creation.
Example Comparing the Two Approaches
public class StringCreation {
public static void main(String[] args) {
String a = "Java";
String b = "Java";
String c = new String("Java");
System.out.println(a == b);
System.out.println(a == c);
System.out.println(a.equals(c));
}
}
Output:
true
false
true
Explanation:
a == b is true because both variables refer to the same pooled literal in this example.
a == c is false because c refers to a separately created String object.
a.equals(c) is true because the character sequences are equal.
5. Understanding String Immutability
One of the most important characteristics of Java strings is immutability. After a String object is created, its contents cannot be changed. Methods such as toUpperCase(), replace(), and concat() return a result rather than changing the original object.
Example
public class StringImmutability {
public static void main(String[] args) {
String text = "Java";
text.concat(" Programming");
System.out.println(text);
text = text.concat(" Programming");
System.out.println(text);
}
}
Output:
Java
Java Programming
Explanation:
- The first
concat() call creates a result, but the program does not store or use that result.
- The original
text variable therefore still refers to "Java".
- The second call assigns the returned string to
text.
- The variable now refers to the new string
"Java Programming"; the original String object itself has not changed.
Advantages of String Immutability
- Security: Text values used in APIs, file paths, and configuration settings cannot be modified through a String reference after creation.
- Thread safety: Immutable String objects can be safely shared between threads without synchronization to protect their contents.
- String pooling: Reusing immutable string literals is practical because their character contents cannot change.
- Predictability: A method receiving a String cannot alter that object's character sequence.
6. String Length
The length() method returns the number of UTF-16 code units in a String. For ordinary English text, this usually matches the number of visible characters. Some Unicode characters, such as many emoji, require two UTF-16 code units, so length() is not always the same as the number of user-perceived characters.
Example
public class StringLengthExample {
public static void main(String[] args) {
String language = "Java";
String message = "Learn Java";
System.out.println(language.length());
System.out.println(message.length());
}
}
Output:
4
10
Spaces are included in the length. For example, "Learn Java" contains nine letters and one space, giving a length of ten.
7. Accessing Characters in a String
The charAt() method returns the UTF-16 code unit at a specified zero-based index. The first position is index 0, and the final position is length() - 1.
Example
public class CharacterAccess {
public static void main(String[] args) {
String language = "Java";
System.out.println(language.charAt(0));
System.out.println(language.charAt(2));
System.out.println(language.charAt(language.length() - 1));
}
}
Output:
J
v
a
If the index is negative or greater than or equal to the string length, Java throws a StringIndexOutOfBoundsException.
8. Combining Strings
String concatenation combines multiple pieces of text into one resulting string. Java supports the + operator and the concat() method.
8.1 Using the + Operator
String firstName = "Neha";
String lastName = "Sharma";
String fullName = firstName + " " + lastName;
System.out.println(fullName);
Output:
Neha Sharma
8.2 Using concat()
String first = "Core";
String second = " Java";
String result = first.concat(second);
System.out.println(result);
Output:
Core Java
8.3 Combining Strings with Numbers
String course = "Java";
int duration = 3;
System.out.println(course + " course duration: " + duration + " months");
Output:
Java course duration: 3 months
When combining numbers and strings, pay attention to operator order because the + operator can mean numeric addition or string concatenation.
System.out.println(10 + 20 + "Java");
System.out.println("Java" + 10 + 20);
Output:
30Java
Java1020
9. Comparing Strings
String comparison is a fundamental part of string handling. Java provides different ways to compare reference identity and text content.
9.1 Using equals()
The equals() method checks whether two strings contain the same sequence of characters, considering case.
String a = "Java";
String b = "Java";
System.out.println(a.equals(b));
Output:
true
9.2 Using equalsIgnoreCase()
The equalsIgnoreCase() method compares strings without considering differences between uppercase and lowercase letters for the comparison.
String a = "JAVA";
String b = "Java";
System.out.println(a.equalsIgnoreCase(b));
Output:
true
9.3 Using ==
The == operator compares references when used with String variables. It checks whether both references identify the same object, not whether their contents are equal.
String a = new String("Java");
String b = new String("Java");
System.out.println(a == b);
System.out.println(a.equals(b));
Output:
false
true
9.4 Using compareTo()
The compareTo() method compares strings lexicographically using their UTF-16 code units. It returns zero if the strings compare as equal, a negative value if the first string comes before the second, and a positive value if it comes after.
String a = "Apple";
String b = "Banana";
System.out.println(a.compareTo(b));
System.out.println(a.compareTo("Apple"));
Output:
-1
0
For the first comparison, the result is negative because the first differing character in "Apple" precedes the corresponding character in "Banana". Programs should generally test whether the result is negative, zero, or positive rather than relying on a particular nonzero number.
10. Commonly Used String Methods
The String class provides many methods for processing text. The following table lists frequently used methods.
| Method |
Purpose |
Example |
length() |
Returns the number of UTF-16 code units |
"Java".length() |
charAt(index) |
Returns the code unit at an index |
"Java".charAt(1) |
equals(str) |
Compares string contents with case sensitivity |
a.equals(b) |
equalsIgnoreCase(str) |
Compares without case sensitivity |
a.equalsIgnoreCase(b) |
toUpperCase() |
Returns a version converted to uppercase using the default locale |
"java".toUpperCase() |
toLowerCase() |
Returns a version converted to lowercase using the default locale |
"JAVA".toLowerCase() |
trim() |
Removes leading and trailing characters with code points at or below U+0020 |
" Java ".trim() |
strip() |
Removes leading and trailing Unicode whitespace as defined by Java |
" Java ".strip() |
contains(sequence) |
Checks whether a character sequence occurs in the string |
"Core Java".contains("Java") |
startsWith(prefix) |
Checks whether a string begins with a prefix |
"Java".startsWith("Ja") |
endsWith(suffix) |
Checks whether a string ends with a suffix |
"Java".endsWith("va") |
indexOf(value) |
Returns the first matching index or -1 if absent |
"banana".indexOf("a") |
lastIndexOf(value) |
Returns the last matching index or -1 if absent |
"banana".lastIndexOf("a") |
substring(begin, end) |
Returns a portion from the start index up to, but not including, the end index |
"Programming".substring(0, 7) |
replace(old, new) |
Replaces matching literal character sequences |
"Java".replace("J", "L") |
split(regex) |
Splits a string using a regular expression |
"a,b".split(",") |
isEmpty() |
Checks whether the length is zero |
"".isEmpty() |
isBlank() |
Checks whether the string is empty or contains only whitespace |
" ".isBlank() |
Note: strip() and isBlank() were introduced in Java 11. Use them when the project's Java version supports these methods.
```html
11. Converting Strings to Uppercase and Lowercase
Java provides toUpperCase() and toLowerCase() methods to convert text into uppercase or lowercase. These methods return a new string and do not modify the original String object.
Example
public class CaseConversion {
public static void main(String[] args) {
String text = "Learning Core Java";
System.out.println(text.toUpperCase());
System.out.println(text.toLowerCase());
System.out.println(text);
}
}
Output:
LEARNING CORE JAVA
learning core java
Learning Core Java
Important: Case conversion can depend on locale. For language-independent identifiers, consider using toLowerCase(Locale.ROOT) or toUpperCase(Locale.ROOT) where appropriate.
12. Removing Leading and Trailing Whitespace
Java provides trim() and strip() to remove certain whitespace characters from the beginning and end of a string. Neither method removes whitespace from the middle of the string.
public class WhitespaceExample {
public static void main(String[] args) {
String text = " Core Java ";
System.out.println("Original: [" + text + "]");
System.out.println("Trimmed: [" + text.trim() + "]");
System.out.println("Stripped: [" + text.strip() + "]");
}
}
Output:
Original: [ Core Java ]
Trimmed: [Core Java]
Stripped: [Core Java]
trim() removes leading and trailing characters whose code points are at or below U+0020. strip() uses Java's Unicode whitespace definition and is available from Java 11.
13. Searching Within Strings
Java offers methods to search for characters and sequences of characters. These methods are useful when checking whether a string contains particular text or finding the position of a value.
Example
public class StringSearch {
public static void main(String[] args) {
String message = "Java makes programming easier";
System.out.println(message.contains("programming"));
System.out.println(message.startsWith("Java"));
System.out.println(message.endsWith("easier"));
System.out.println(message.indexOf("makes"));
System.out.println(message.indexOf("Python"));
}
}
Output:
true
true
true
5
-1
The indexOf() method returns the first matching position. If the requested text is not found, it returns -1.
14. Extracting a Substring
The substring() method extracts part of a string. It supports a starting index and, optionally, an ending index. The starting index is included, while the ending index is excluded.
public class SubstringExample {
public static void main(String[] args) {
String language = "Programming";
System.out.println(language.substring(0, 7));
System.out.println(language.substring(7));
}
}
Output:
Program
ming
Invalid substring indexes cause a StringIndexOutOfBoundsException. Always ensure the indexes are within the valid range.
15. Replacing Text in a String
The replace() method returns a new string in which matching characters or literal character sequences are replaced. For pattern-based replacements, Java provides replaceAll() and replaceFirst(), which use regular expressions.
public class StringReplaceExample {
public static void main(String[] args) {
String text = "I like Python";
String updated = text.replace("Python", "Java");
System.out.println(updated);
System.out.println(text);
}
}
Output:
I like Java
I like Python
The original string remains unchanged because String objects are immutable.
16. Splitting a String into Parts
The split() method divides a string into an array of strings using a regular expression as the delimiter. This is useful for processing comma-separated values, words, and simple structured text.
public class StringSplitExample {
public static void main(String[] args) {
String languages = "Java,Python,JavaScript";
String[] items = languages.split(",");
for (String item : items) {
System.out.println(item);
}
}
}
Output:
Java
Python
JavaScript
Because split() accepts a regular expression, characters such as a period must be escaped when intended as literal delimiters. For example, use text.split("\\.") to split on a literal period. The one-argument form also removes trailing empty results; use split(regex, -1) when trailing empty fields must be preserved.
17. Checking Empty and Blank Strings
An empty string has a length of zero. A blank string is either empty or contains only characters recognized as whitespace by the relevant Java method.
public class EmptyBlankExample {
public static void main(String[] args) {
String first = "";
String second = " ";
String third = "Java";
System.out.println(first.isEmpty());
System.out.println(second.isEmpty());
System.out.println(second.isBlank());
System.out.println(third.isBlank());
}
}
Output:
true
false
true
false
isEmpty() checks whether the length is zero. isBlank() checks whether the string is empty or contains only whitespace according to Java's definition. The isBlank() method requires Java 11 or later.
18. Converting Other Data Types into Strings
Java applications frequently need to convert numbers, Boolean values, and other objects into text. The String.valueOf() method provides convenient conversions for many common data types.
public class StringConversion {
public static void main(String[] args) {
int age = 25;
double price = 149.50;
boolean active = true;
String ageText = String.valueOf(age);
String priceText = String.valueOf(price);
String activeText = String.valueOf(active);
System.out.println(ageText);
System.out.println(priceText);
System.out.println(activeText);
}
}
Output:
25
149.5
true
For formatting numbers, dates, and other values in a consistent presentation, Java also provides formatting methods and classes. Choose a formatting approach that matches the application's requirements.
19. Difference Between String, StringBuilder, and StringBuffer
Java provides three commonly used classes for working with text: String, StringBuilder, and StringBuffer. The main difference is whether the character sequence can be modified after the object is created.
| Feature |
String |
StringBuilder |
StringBuffer |
| Mutability |
Immutable |
Mutable |
Mutable |
| Typical use |
Text values that do not need repeated modification |
Repeated text modification, commonly in single-threaded code |
Mutable text when synchronized methods are required |
| Modification |
Operations return new strings |
Methods modify the existing builder |
Methods modify the existing buffer |
| Synchronization |
Immutable contents can be shared safely |
Not synchronized by default |
Many methods are synchronized |
| Common methods |
concat(), substring(), replace() |
append(), insert(), delete(), reverse() |
append(), insert(), delete(), reverse() |
StringBuilder Example
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder result = new StringBuilder();
result.append("Core");
result.append(" ");
result.append("Java");
result.append(" Training");
System.out.println(result);
}
}
Output:
Core Java Training
StringBuilder is often suitable when many modifications are needed, such as constructing text inside a loop. StringBuffer provides synchronized operations, but synchronization alone does not automatically make every multi-step operation logically thread-safe.
20. Reading String Input Using Scanner
The Scanner class can read text entered by a user. The next() method reads the next token, usually stopping at whitespace, while nextLine() reads the remaining contents of the current line.
import java.util.Scanner;
public class StringInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your full name: ");
String name = scanner.nextLine();
System.out.println("Welcome, " + name);
scanner.close();
}
}
Sample Input:
Priya Sharma
Output:
Enter your full name: Priya Sharma
Welcome, Priya Sharma
When combining numeric input methods such as nextInt() with nextLine(), remember that the newline left after reading the number may be consumed by the next line-reading call. Read or consume the remaining newline when needed.
21. Handling Null Strings Safely
A String reference can contain null, which means it does not refer to a String object. Calling an instance method on a null reference causes a NullPointerException.
Example
public class NullStringExample {
public static void main(String[] args) {
String name = null;
if (name != null) {
System.out.println(name.length());
} else {
System.out.println("Name has not been provided.");
}
}
}
Output:
Name has not been provided.
Do not confuse null, an empty string "", and a blank string such as " ". They represent different situations and may require different validation rules.
22. Common String Handling Errors
| Error |
Cause |
Solution |
Using == for content comparison |
It checks reference identity rather than String content equality |
Use equals() for exact content comparison |
| Ignoring immutability |
Assuming methods such as replace() modify the original string |
Store the returned string if the result is needed |
| Invalid character index |
Passing an index outside the valid range to charAt() |
Check that the index is at least zero and less than length() |
| Invalid substring range |
Using an invalid start or end index |
Validate both indexes and ensure the start does not exceed the end |
| Calling methods on null |
The variable does not reference a String object |
Validate the reference before calling instance methods |
| Incorrect split delimiter |
Using a regular-expression character as if it were literal |
Escape regex metacharacters when required |
| Excessive concatenation in loops |
Repeatedly creating intermediate strings |
Consider using StringBuilder |
| Unexpected whitespace |
Input contains leading, trailing, or internal whitespace |
Apply appropriate trimming, stripping, and validation rules |
23. Best Practices for String Handling
- Use string literals for ordinary text values rather than creating unnecessary String objects with
new.
- Use
equals() to compare string contents and == only when reference identity is intended.
- Remember that String objects are immutable and store the result of methods when needed.
- Use
StringBuilder for repeated concatenation, especially inside loops.
- Check for null references before calling String instance methods.
- Validate indexes before using
charAt() or substring().
- Use
strip() or trim() according to the whitespace behavior required by the application.
- Remember that
split() accepts a regular expression, not just a plain delimiter.
- Use locale-aware rules where text conversion or sorting depends on a particular language.
- Do not assume that
length() always equals the number of visible Unicode characters.
- Prefer clear, readable code over complicated chains of string operations.
- Validate user input before using it in database queries, file operations, or security-sensitive logic.
24. Practical Mini Project: Student Information Formatter
Project Objective: Create a Java program that accepts a student's name and course, removes unnecessary leading and trailing whitespace, formats the student's name, and displays useful information about the resulting strings.
Program
import java.util.Scanner;
public class StudentInformationFormatter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter student name: ");
String name = scanner.nextLine().strip();
System.out.print("Enter course name: ");
String course = scanner.nextLine().strip();
if (name.isBlank() || course.isBlank()) {
System.out.println("Name and course are required.");
} else {
String formattedName = name.toUpperCase();
System.out.println("Student: " + formattedName);
System.out.println("Course: " + course);
System.out.println("Name length: " + name.length());
System.out.println(
"Course contains Java: " +
course.toLowerCase().contains("java")
);
}
scanner.close();
}
}
Sample Input:
Enter student name: Priya Sharma
Enter course name: Core Java Training
Sample Output:
Student: PRIYA SHARMA
Course: Core Java Training
Name length: 12
Course contains Java: true
Concepts Practiced
- Reading strings from user input.
- Removing leading and trailing whitespace.
- Checking for empty or blank input.
- Converting text to uppercase and lowercase.
- Finding string length.
- Searching for a word within a string.
- Combining strings to display formatted information.
Version note: This project uses strip() and isBlank(), so it requires Java 11 or later.
25. Practice Exercises
- Declare a String variable containing your name and display it on the console.
- Write a program to find and print the length of a string.
- Convert a sentence into uppercase and lowercase.
- Compare two strings using both
equals() and ==, and explain the difference.
- Extract a specific word from a sentence using
substring().
- Replace one word with another using
replace().
- Count the number of occurrences of a particular character in a string.
- Split a comma-separated list of programming languages into individual values.
- Read a full name using
Scanner.nextLine() and display it in uppercase.
- Write a program that checks whether a string is empty, blank, or contains text.
- Build a sentence using
StringBuilder and its append() method.
- Write a program that safely handles a String reference that might be null.
26. Interview Questions and Answers
Q1. What is a String in Java?
A String is an object of the java.lang.String class that represents a sequence of characters.
Q2. Is String a primitive data type?
No. String is a reference type implemented as a Java class.
Q3. Why are String objects immutable?
Immutability supports safe sharing, predictable behavior, and the reuse of string literals. It also helps prevent a String's contents from changing unexpectedly after it is created.
Q4. What is the difference between == and equals()?
For String references, == checks whether both references point to the same object. equals() checks whether the strings contain the same character sequence.
Q5. What is the String pool?
The String pool is a mechanism used to reuse canonical String instances, particularly string literals. It can reduce duplicate string objects for equal literal values.
Q6. What does length() return?
It returns the number of UTF-16 code units in the string. Some Unicode characters require two code units, so the value may differ from the number of visible characters.
Q7. What is the difference between isEmpty() and isBlank()?
isEmpty() returns true only when the string length is zero. isBlank() returns true when the string is empty or contains only whitespace recognized by Java. isBlank() is available from Java 11.
Q8. What is the difference between String and StringBuilder?
String is immutable, while StringBuilder is mutable. StringBuilder is often more efficient when many text modifications are required.
Q9. What does substring() do?
It returns a new string containing the selected portion of the original string. The starting index is included, and the ending index, when supplied, is excluded.
Q10. What does indexOf() return when a value is not found?
It returns -1.
Q11. What is the difference between trim() and strip()?
trim() removes leading and trailing characters with code points at or below U+0020. strip() uses Java's Unicode whitespace definition and was introduced in Java 11.
Q12. Why can split(".") behave unexpectedly?
The period is a regular-expression metacharacter that matches any character. To split on a literal period, use split("\\.").
Q13. What happens when a String method is called on null?
A NullPointerException occurs because the reference does not point to a String object.
Q14. How can you concatenate many strings efficiently?
For repeated modifications, especially inside loops, use StringBuilder and its append() method.
Q15. How do you compare strings without considering case?
Use equalsIgnoreCase() for a simple case-insensitive equality check. More complex language-specific comparisons may require locale-aware or Unicode-aware techniques.
27. Quick Revision Checklist
- String is a reference type in Java.
- String objects are immutable.
- String literals can be reused through the String pool.
length() returns the number of UTF-16 code units.
charAt() accesses a code unit at a zero-based index.
equals() compares content; == compares reference identity.
concat() and other transformation methods return results rather than changing the original string.
substring() extracts a section of text.
indexOf() returns -1 if the requested value is not found.
split() uses a regular expression as its delimiter.
StringBuilder is useful for repeated text modifications.
- Null references must be checked before calling instance methods.
strip() and isBlank() require Java 11 or later.
28. Additional Learning Resources
29. Conclusion
String handling is a fundamental part of Java programming because applications regularly work with text, user input, identifiers, and messages. Understanding String creation, immutability, comparison, searching, extraction, replacement, and conversion makes it easier to write reliable and readable programs.
For repeated text modifications, StringBuilder can be a suitable choice. For ordinary text values, String remains the standard option. Practicing these methods with small programs and real-world examples will help build a strong foundation for advanced Core Java topics.
Continue learning through the JustAcademy Core Java Training Course or register for a course demo.