Java provides a rich set of built-in methods in the String class that allow developers to perform various operations such as finding characters, extracting substrings, comparing strings, replacing text, converting case, and splitting strings. Understanding these methods is essential for writing efficient and maintainable Java programs.
In this article, we will explore the most commonly used String methods in Java with syntax, examples, outputs, explanations, common mistakes, best practices, and FAQs.
Table of Contents
What is a String in Java?
A String is a sequence of characters enclosed within double quotation marks.Example:
Strings in Java are immutable, which means their values cannot be changed after creation. Whenever a modification is performed, a new String object is created.String language = "Java";
length() Method
The length() method is used to determine the number of characters present in a string. It is one of the most commonly used String methods and is often used for validation, loops, and text processing operations.The method returns an integer value representing the total length of the string.
Example:
// Java program to implement length() method
public class LengthExample {
public static void main(String[] args) {
String str = "Java Programming";
System.out.println(str.length());
}
}
Output:
Explanation:16
The string contains 16 characters, including the space between the words. The length() method counts every character present in the string.
charAt() Method
The charAt() method is used to access an individual character from a string. It accepts an index value and returns the character located at that position.Since string indexing starts from 0, the first character is always stored at index 0.
Example:
// Java program to implement charAt() method
public class CharAtExample {
public static void main(String[] args) {
String str = "Java";
System.out.println(str.charAt(2));
}
}
Output:
Explanation:v
The character 'v' is located at index 2 in the string "Java". Therefore, the method returns v.
substring() Method
The substring() method extracts a specific portion of a string and returns it as a new string. It is commonly used when only a part of the text is required.The original string remains unchanged because String objects are immutable.
Example:
// Java program to implement substring() method
public class SubstringExample {
public static void main(String[] args) {
String str = "Java Programming";
System.out.println(str.substring(5));
}
}
Output:
Programming
Explanation:The method extracts all characters starting from index 5 until the end of the string and returns them as a new string.
equals() Method
The equals() method compares the contents of two strings. Unlike the == operator, it compares actual character values rather than memory references.This method returns true if both strings contain exactly the same sequence of characters.
Example:
// Java program to implement equals() method
public class EqualsExample {
public static void main(String[] args) {
String str1 = "Java";
String str2 = "Java";
System.out.println(str1.equals(str2));
}
}
Output:
Explanation:true
Both strings contain the same characters in the same order, so the method returns true.
equalsIgnoreCase() Method
The equalsIgnoreCase() method compares two strings while ignoring differences in uppercase and lowercase letters.It is useful when user input should be compared without considering letter case.
Example:
// Java program to implement equalsIgnoreCase() method
public class EqualsIgnoreCaseExample {
public static void main(String[] args) {
String str1 = "JAVA";
String str2 = "java";
System.out.println(str1.equalsIgnoreCase(str2));
}
}
Output:
Explanation:true
Although the letter cases differ, the characters are the same. Therefore, the method returns true.
toUpperCase() Method
The toUpperCase() method converts all lowercase characters in a string into uppercase characters.It is commonly used when performing case-insensitive comparisons or formatting text.
Example:
// Java program to implement toUpperCase() method
public class UpperCaseExample {
public static void main(String[] args) {
String str = "java";
System.out.println(str.toUpperCase());
}
}
Output:
Explanation:JAVA
All lowercase letters are converted into their uppercase equivalents, producing the string "JAVA".
toLowerCase() Method
The toLowerCase() method converts all uppercase characters in a string into lowercase characters.This method is frequently used when standardizing user input before comparison.
Example:
// Java program to implement toLowerCase() method
public class LowerCaseExample {
public static void main(String[] args) {
String str = "JAVA";
System.out.println(str.toLowerCase());
}
}
Output:
Explanation:java
Each uppercase letter is converted into lowercase, resulting in the string "java".
contains() Method
The contains() method checks whether a string contains a particular sequence of characters.It returns true if the specified text exists inside the string; otherwise, it returns false.
Example:
// Java program to implement contains() method
public class ContainsExample {
public static void main(String[] args) {
String str = "Java Programming";
System.out.println(str.contains("Program"));
}
}
Output:
Explanation:true
The substring "Program" exists inside "Java Programming", so the method returns true.
startsWith() Method
The startsWith() method checks whether a string begins with a specified sequence of characters.This method is useful for validating prefixes such as URLs, file paths, or identifiers.
Example:
// Java program to implement startsWith() method
public class StartsWithExample {
public static void main(String[] args) {
String str = "Java Programming";
System.out.println(str.startsWith("Java"));
}
}
Output:
Explanation:true
Since the string begins with "Java", the method returns true.
endsWith() Method
The endsWith() method checks whether a string ends with a specified sequence of characters.It is commonly used for validating file extensions and specific suffixes.
Example:
// Java program to implement endsWith() method
public class EndsWithExample {
public static void main(String[] args) {
String str = "Java Programming";
System.out.println(str.endsWith("Programming"));
}
}
Output:
Explanation:true
The string ends with "Programming", so the method returns true.
indexOf() Method
The indexOf() method returns the position of the first occurrence of a specified character or substring.If the specified value is not found, the method returns -1.
Example:
// Java program to implement indexOf() method
public class IndexOfExample {
public static void main(String[] args) {
String str = "Java Programming";
System.out.println(str.indexOf("Program"));
}
}
Output:
Explanation:5
The substring "Program" begins at index 5, so the method returns 5.
replace() Method
The replace() method replaces specified characters or substrings with new values.Since Strings are immutable, the method returns a new string containing the modifications.
Example:
// Java program to implement replace() method
public class ReplaceExample {
public static void main(String[] args) {
String str = "Java Programming";
System.out.println(str.replace("Java", "Python"));
}
}
Output:
Explanation:Python Programming
The word "Java" is replaced with "Python" and a new string is returned.
trim() Method
The trim() method removes whitespace characters from the beginning and end of a string.It is commonly used when processing user input to eliminate unwanted spaces.
Example:
// Java program to implement trim() method
public class TrimExample {
public static void main(String[] args) {
String str = " Java ";
System.out.println(str.trim());
}
}
Output:
Explanation:Java
The spaces before and after the word are removed. The spaces inside a string would remain unchanged.
isEmpty() Method
The isEmpty() method checks whether a string contains zero characters.It is often used during form validation and input checking.
Example:
// Java program to implement isEmpty() method
{
public static void main(String[] args) {
String str = "";
System.out.println(str.isEmpty());
}
}
Output:
Explanation:true
Since the string contains no characters, the method returns true.
split() Method
The split() method divides a string into multiple parts based on a specified delimiter.The method returns an array containing all the separated values.
Example:
// Java program to implement split() method
public class SplitExample {
public static void main(String[] args) {
String str = "Java,Python,C++";
String[] languages = str.split(",");
for(String language : languages) {
System.out.println(language);
}
}
}
Output:
Explanation:Java
Python
C++
The comma acts as a separator, causing the string to be split into three separate elements.
Common Mistakes
1. Using == Instead of equals(): The == operator compares object references rather than actual string content. This may produce incorrect results even when two strings contain identical characters. Always use the equals() method when comparing string values.2. Ignoring String Immutability: Methods such as replace(), toUpperCase(), and trim() return new String objects rather than modifying the original string. Failing to store the returned value often leads to unexpected results.
3. Accessing Invalid Indexes: Using an invalid index with methods such as charAt() causes a StringIndexOutOfBoundsException. Always verify that the index falls within the valid range of the string.
4. Calling Methods on Null Strings: Invoking String methods on a null reference causes a NullPointerException.
Always check whether a string is null before calling its methods.
Best Practices
- Use equals() for Content Comparison: Always use equals() or equalsIgnoreCase() when comparing string values.
- Store Returned Values: Remember that String methods return new objects. Store the returned value whenever modifications are required.
- Validate Index Values: Check indexes before using methods such as charAt() and substring().
- Use StringBuilder for Frequent Modifications: When performing repeated concatenation or modification operations, StringBuilder is more efficient than String.
- Handle Null Values Carefully: Always validate user input and null references before performing String operations.
Conclusion
The String class provides numerous built-in methods that simplify text manipulation in Java. Methods such as length(), charAt(), substring(), equals(), replace(), and split() are widely used in real-world applications.A strong understanding of these methods helps developers write cleaner, more efficient, and more reliable Java programs.
Frequently Asked Questions
1. What is the most commonly used String method in Java?2. What is the difference between equals() and ==?The length() method is one of the most frequently used methods because it returns the number of characters in a string.
3. Does substring() modify the original string?The equals() method compares string content, while == compares object references.
4. What does trim() do in Java?No. Since Strings are immutable, substring() returns a new String object without modifying the original one.
5. Which method converts a string to uppercase?The trim() method removes leading and trailing spaces from a string.
The toUpperCase() method converts all characters in a string to uppercase.
0 Comments