π§΅ Java String Methods: Complete Guide with Examples, Syntax & Explanations
π§² Introduction β Why Java String Methods Matter
In Java, String
is one of the most widely used classes. Whether you’re handling user input, displaying messages, or parsing files β strings are everywhere. But raw strings are just data β string methods give them power. π‘
By mastering Java String methods, youβll be able to:
- β Manipulate text efficiently
- β Search, compare, and extract substrings
- β Format and clean input data
π Java
String
is immutable, meaning every modification creates a new object.
π What is a Java String?
A String
in Java is a sequence of characters, treated as an object. You create strings using:
String message = "Hello, Java!";
π Common Java String Methods
Below is a categorized table of popular String methods:
π§© Method | π Purpose |
---|---|
length() | Returns the number of characters |
charAt(int index) | Returns the character at a given index |
substring(int begin, int end) | Extracts a portion of the string |
toLowerCase() / toUpperCase() | Converts case |
trim() | Removes whitespace |
replace(old, new) | Replaces characters |
equals(str) / equalsIgnoreCase(str) | Compares strings |
contains(str) | Checks if substring exists |
startsWith() / endsWith() | Checks prefix/suffix |
split(regex) | Splits string based on regex |
indexOf() / lastIndexOf() | Finds character/index |
isEmpty() | Checks if string is empty |
concat(str) | Concatenates two strings |
π Examples of Java String Methods
β
1. length()
β Find the String Length
String text = "Java";
System.out.println(text.length());
Output:
4
β
Explanation: Returns the number of characters in "Java"
.
β
2. charAt(int index)
β Access Character by Index
String name = "Developer";
System.out.println(name.charAt(0));
Output:
D
β Explanation: Indexing starts at 0, so this prints the first character.
β
3. substring(int begin, int end)
String title = "Full Stack Developer";
System.out.println(title.substring(0, 4));
Output:
Full
β Explanation: Extracts characters from index 0 to 3 (excluding index 4).
β
4. toLowerCase()
and toUpperCase()
String lang = "Java Programming";
System.out.println(lang.toLowerCase());
System.out.println(lang.toUpperCase());
Output:
java programming
JAVA PROGRAMMING
β Explanation: Converts the string to lower and upper case.
β
5. trim()
β Remove Leading/Trailing Whitespaces
String input = " Hello World! ";
System.out.println(input.trim());
Output:
Hello World!
β Explanation: Removes extra spaces from start and end.
β
6. replace()
β Replace Characters/Substrings
String sentence = "Java is awesome!";
System.out.println(sentence.replace("awesome", "powerful"));
Output:
Java is powerful!
β
Explanation: Replaces awesome
with powerful
.
β
7. equals()
and equalsIgnoreCase()
String a = "Java";
String b = "java";
System.out.println(a.equals(b)); // false
System.out.println(a.equalsIgnoreCase(b)); // true
β
Explanation: equals()
is case-sensitive, equalsIgnoreCase()
is not.
β
8. contains()
β Search for Substring
String text = "Java Backend Developer";
System.out.println(text.contains("Backend"));
Output:
true
β Explanation: Confirms if “Backend” exists in the string.
β
9. startsWith()
and endsWith()
String url = "https://openai.com";
System.out.println(url.startsWith("https"));
System.out.println(url.endsWith(".org"));
Output:
true
false
β Explanation: Validates the beginning and end of a string.
β
10. split()
β Break String into Parts
String data = "apple,banana,grape";
String[] fruits = data.split(",");
for (String fruit : fruits) {
System.out.println(fruit);
}
Output:
apple
banana
grape
β
Explanation: Splits the string into an array using ,
as the delimiter.
β
11. indexOf()
and lastIndexOf()
String quote = "Think Twice, Code Once";
System.out.println(quote.indexOf("e")); // 11
System.out.println(quote.lastIndexOf("e")); // 18
β Explanation: Finds the first and last position of a character.
β
12. isEmpty()
String emptyStr = "";
System.out.println(emptyStr.isEmpty());
Output:
true
β Explanation: Checks if the string is empty (length is 0).
β
13. concat()
β Append Strings
String first = "Hello";
String second = " World";
System.out.println(first.concat(second));
Output:
Hello World
β Explanation: Appends two strings.
π‘ Java String Method Tips
- β
Use
equals()
instead of==
for string comparison. - β
Chain methods like
str.trim().toLowerCase()
for better readability. - β οΈ Avoid modifying large strings repeatedly β use
StringBuilder
for better performance. - π Strings are immutable. Each method returns a new String, not modifying the original.
π§ Summary β Java String Methods at a Glance
Java String methods provide powerful tools to manipulate, format, analyze, and transform text data in your applications. Since strings are immutable, each method returns a new string, ensuring thread-safety and data integrity.
Hereβs what youβve learned:
- β
String Basics: Strings are objects and created using
String
class. - β
Key Methods Covered:
length()
,charAt()
,substring()
,toUpperCase()
,trim()
,replace()
,equals()
,split()
,indexOf()
, and many more. - β Real-World Examples: Each method included syntax, output, and detailed explanation.
- β οΈ Best Practices: Use
equals()
for comparison, avoid==
for content check, and preferStringBuilder
for heavy string manipulation.
Mastering these methods equips you to handle text data efficiently β an essential skill for any Java developer.
β FAQs on Java String Methods
β What is the difference between equals()
and ==
?
equals()
compares content, while ==
compares memory addresses (references).
β Can we modify a String in Java?
No, Strings are immutable. Any modification returns a new string.
β Which is better: +
operator or concat()
?
Both work similarly. However, for multiple concatenations, prefer StringBuilder
.
β What happens if charAt()
index is out of bounds?
It throws a StringIndexOutOfBoundsException
.
β How do I remove all spaces from a string?
Use: str.replace(" ", "")
β it removes all spaces.
Share Now :