java
- IntroductionInstallation and SetupJava Syntax and StructureRunning Your First ProgramJava VariablesData Types in JavaOperators in JavaJava Input and OutputControl StatementsLoops in JavaMethods in Java (Functions)Arrays in JavaString Handling in JavaOOPS Concept in JavaClasses and ObjectsConstructor and Constructor Overloadingthis KeywordStatic MembersInheritanceAggregation in JavaMethod OverloadingMethod Overridingsuper KeywordFinal Keyword with Class, Method, and VariablesAccess Modifiers in javaEncapsulation in Java Polymorphism in JavaAbstraction in JavaAbstract ClassesInterfaces in JavaDifference between Abstract Class and Interface Nested and Inner Classes Exception HandlingJava PackagesWrapper Classes and AutoboxingJava Collections FrameworkFile Handling in JavaMultithreadingBasics of Java Memory Management and Garbage CollectionJava JDBC
Java String Handling Tutorial for Beginners
Last Updated on: 23rd Oct 2025 16:40:59 PM
Welcome to this beginner-friendly tutorial on String Handling in Java! Strings are one of the most commonly used data types in Java, representing sequences of characters (e.g., "Hello"). They are widely used for text processing, user input, and output. This tutorial covers the basics of strings, the String class, and its key methods with clear explanations and practical examples. You can run these examples in any Java environment (e.g., Eclipse, IntelliJ, or Repl.it).
By the end, you’ll understand how to create, manipulate, and use strings effectively. Let’s dive in!
What Are Strings in Java?
A String is a sequence of characters (e.g., "Java is fun"). In Java, strings are objects of the String class, not primitive types. They are:
-
Immutable: Once created, a string’s value cannot be changed. Operations create new strings.
-
Stored in String Pool: Java optimizes memory by reusing string literals.
-
Part of java.lang: No import needed to use the String class.
Real-World Analogy: A string is like a name tag—you can read it, compare it, or combine it with others, but you can’t change the letters on the tag itself.
1. Creating Strings
Strings can be created in two main ways:
-
String Literal: Using double quotes (stored in the string pool).
-
Using new Keyword: Creates a new String object in memory.
Example: Creating Strings
public class StringCreation {
public static void main(String[] args) {
// String literal
String str1 = "Hello";
// Using new keyword
String str2 = new String("World");
System.out.println("String 1: " + str1); // Hello
System.out.println("String 2: " + str2); // World
}
}
Output:
String 1: Hello
String 2: World
Explanation:
-
str1 uses a literal, stored in the string pool for efficiency.
-
str2 creates a new object, less common but valid.
-
Use literals unless you specifically need a new object.
2. String Immutability
Strings are immutable, meaning their content cannot be modified. Methods that seem to change a string actually create a new one.
Example: Immutability
public class StringImmutability {
public static void main(String[] args) {
String str = "Hello";
str = str.concat(" World"); // Creates a new string
System.out.println(str); // Hello World
}
}
Output:
Hello World
Explanation:
-
concat doesn’t modify str; it returns a new string.
-
str = str.concat(" World") reassigns str to the new string.
Real-World Analogy: Like writing a new name tag instead of erasing the old one.
3. Common String Methods
The String class provides many methods for manipulating and inspecting strings. Below are the most commonly used methods, grouped by functionality, with examples.
3.1 Length and Character Access
|
Method |
Description |
Return Type |
|---|---|---|
|
length() |
Returns the number of characters |
int |
|
charAt(int index) |
Returns the character at the specified index |
char |
Example :
public class LengthCharAtExample {
public static void main(String[] args) {
String str = "Java";
System.out.println("Length: " + str.length()); // 4
System.out.println("Character at index 1: " + str.charAt(1)); // a
}
}
Output:
Length: 4
Character at index 1: a
Explanation:
-
length() counts characters (including spaces if present).
-
charAt(1) returns the character at index 1 (0-based indexing).
Note: charAt throws StringIndexOutOfBoundsException if the index is invalid (e.g., str.charAt(4)).
3.2 String Comparison
|
Method |
Description |
Return Type |
|---|---|---|
|
equals(Object obj) |
Checks if two strings have the same content |
boolean |
|
equalsIgnoreCase(String str) |
Compares strings, ignoring case |
boolean |
|
compareTo(String str) |
Compares lexicographically (dictionary order) |
int |
|
compareToIgnoreCase(String str) |
Compares lexicographically, ignoring case |
int |
Example :
public class ComparisonExample {
public static void main(String[] args) {
String str1 = "Java";
String str2 = "java";
String str3 = "Hello";
// equals
System.out.println("str1 equals str2: " + str1.equals(str2)); // false
System.out.println("str1 equalsIgnoreCase str2: " + str1.equalsIgnoreCase(str2)); // true
// compareTo
System.out.println("str1 compareTo str3: " + str1.compareTo(str3)); // > 0 (Java > Hello)
System.out.println("str3 compareTo str1: " + str3.compareTo(str1)); // < 0 (Hello < Java)
}
}
Output:
str1 equals str2: false
str1 equalsIgnoreCase str2: true
str1 compareTo str3: 3
str3 compareTo str1: -3
Explanation:
-
equals checks exact content (case-sensitive).
-
equalsIgnoreCase ignores case differences.
-
compareTo returns:
-
0 if strings are equal.
-
Positive if the first string is lexicographically greater.
-
Negative if the first string is lexicographically smaller.
-
Real-World Analogy: Like comparing two names in a phone book to sort them.
3.3 String Manipulation
|
Method |
Description |
Return Type |
|---|---|---|
|
concat(String str) |
Concatenates another string to the end |
String |
|
substring(int beginIndex) |
Returns substring from beginIndex to end |
String |
|
substring(int beginIndex, int endIndex) |
Returns substring from beginIndex to endIndex-1 |
String |
|
replace(char oldChar, char newChar) |
Replaces all occurrences of oldChar with newChar |
String |
|
replaceAll(String regex, String replacement) |
Replaces all matches of regex with replacement |
String |
|
toLowerCase() |
Converts to lowercase |
String |
|
toUpperCase() |
Converts to uppercase |
String |
|
trim() |
Removes leading/trailing whitespace |
String |
Example :
public class ManipulationExample {
public static void main(String[] args) {
String str = " Hello Java! ";
System.out.println("Concat: " + str.concat(" World")); // Hello Java! World
System.out.println("Substring (6): " + str.substring(6)); // Java!
System.out.println("Substring (2, 7): " + str.substring(2, 7)); // Hello
System.out.println("Replace 'a' with 'o': " + str.replace('a', 'o')); // Hello Jovo!
System.out.println("ReplaceAll 'Java' with 'World': " + str.replaceAll("Java", "World")); // Hello World!
System.out.println("To Uppercase: " + str.toUpperCase()); // HELLO JAVA!
System.out.println("To Lowercase: " + str.toLowerCase()); // hello java!
System.out.println("Trim: " + str.trim()); // Hello Java!
}
}
Output:
Concat: Hello Java! World
Substring (6): Java!
Substring (2, 7): Hello
Replace 'a' with 'o': Hello Jovo!
ReplaceAll 'Java' with 'World': Hello World!
To Uppercase: HELLO JAVA!
To Lowercase: hello java!
Trim: Hello Java!
Explanation:
-
concat adds a string to the end.
-
substring extracts parts of the string (endIndex is exclusive).
-
replace changes specific characters; replaceAll uses regex for patterns.
-
toLowerCase/toUpperCase change case.
-
trim removes whitespace from the start and end.
Note: All these methods return new strings due to immutability.
3.4 Searching and Testing
|
Method |
Description |
Return Type |
|---|---|---|
|
contains(CharSequence s) |
Checks if string contains the specified sequence |
boolean |
|
startsWith(String prefix) |
Checks if string starts with prefix |
boolean |
|
endsWith(String suffix) |
Checks if string ends with suffix |
boolean |
|
indexOf(int ch) |
Returns index of first occurrence of character |
int |
|
indexOf(String str) |
Returns index of first occurrence of substring |
int |
|
lastIndexOf(int ch) |
Returns index of last occurrence of character |
int |
|
lastIndexOf(String str) |
Returns index of last occurrence of substring |
int |
|
isEmpty() |
Checks if string is empty |
boolean |
Example
public class SearchExample {
public static void main(String[] args) {
String str = "Learning Java is fun";
System.out.println("Contains 'Java': " + str.contains("Java")); // true
System.out.println("Starts with 'Learn': " + str.startsWith("Learn")); // true
System.out.println("Ends with 'fun': " + str.endsWith("fun")); // true
System.out.println("Index of 'a': " + str.indexOf('a')); // 2
System.out.println("Index of 'Java': " + str.indexOf("Java")); // 9
System.out.println("Last index of 'a': " + str.lastIndexOf('a')); // 11
System.out.println("Is empty: " + str.isEmpty()); // false
}
}
Output:
Contains 'Java': true
Starts with 'Learn': true
Ends with 'fun': true
Index of 'a': 2
Index of 'Java': 9
Last index of 'a': 11
Is empty: false
Explanation:
-
contains checks for a substring.
-
startsWith/endsWith test the beginning/end.
-
indexOf/lastIndexOf return -1 if the character/substring isn’t found.
-
isEmpty returns true for "".
3.5 Splitting and Joining
|
Method |
Description |
Return Type |
|---|---|---|
|
split(String regex) |
Splits string into an array based on regex |
String[] |
|
join(CharSequence delimiter, CharSequence... elements) |
Joins strings with a delimiter |
String |
Example
public class SplitJoinExample {
public static void main(String[] args) {
String str = "Apple,Banana,Orange";
// Split
String[] fruits = str.split(",");
System.out.println("Split result:");
for (String fruit : fruits) {
System.out.println(fruit);
}
// Join
String joined = String.join(" - ", fruits);
System.out.println("Joined: " + joined); // Apple - Banana - Orange
}
}
Output:
Split result:
Apple
Banana
Orange
Joined: Apple - Banana - Orange
Explanation:
-
split(",") splits the string at commas into an array.
-
join combines elements with a delimiter.
4. String with User Input
Let’s create a program that uses Scanner to manipulate user-entered strings.
import java.util.Scanner;
public class StringInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Length of name: " + name.length());
System.out.println("Uppercase: " + name.toUpperCase());
System.out.println("Contains 'a': " + name.contains("a"));
System.out.println("First character: " + name.charAt(0));
scanner.close();
}
}
Sample Run:
Enter your name: Alice
Length of name: 5
Uppercase: ALICE
Contains 'a': false
First character: A
Explanation:
-
Scanner reads a line of input.
-
String methods process the input (length, case, etc.).
5. Common Issues and Solutions
-
Problem: StringIndexOutOfBoundsException.
-
Solution: Ensure indices are within 0 to length()-1 for charAt or substring.
-
-
Problem: Null string errors (NullPointerException).
-
Solution: Check for null before using methods (e.g., if (str != null)).
-
-
Problem: Unexpected split results.
-
Solution: Test regex patterns carefully, as special characters (e.g., .) need escaping (e.g., \\.).
-
6. Practice Tips
-
Experiment: Try combining methods (e.g., toLowerCase().contains()).
-
Test Code: Use an online compiler to run examples.
-
Common Mistake: Don’t confuse == with equals for string comparison.
-
Quiz Yourself: What does "Hello".substring(1, 3) return? (Answer: "el")
Summary
-
Strings: Immutable sequences of characters, stored in the string pool.
-
Key Methods:
-
Length/Access: length, charAt.
-
Comparison: equals, equalsIgnoreCase, compareTo.
-
Manipulation: concat, substring, replace, toLowerCase, toUpperCase, trim.
-
Searching: contains, startsWith, endsWith, indexOf, lastIndexOf, isEmpty.
-
Splitting/Joining: split, join.
-
-
Next Steps: Combine strings with arrays, loops, or methods for tasks like parsing or formatting.
You’re now ready to handle strings in Java! Keep practicing, and happy coding! ![]()
.png)