String Methods in Java
In Java, String is one of the most frequently used classes.
Almost every Java program deals with text โ names, input, passwords, messages, file data, etc.
Java provides many built-in String methods to perform operations like:
- Finding length
- Comparing strings
- Extracting characters
- Modifying text
- Searching content
๐ All these methods belong to the String class.
Important Thing to Remember About Strings โ ๏ธ
Strings in Java are immutable.
This means:
- Once a
Stringobject is created, it cannot be changed - Any operation on a String creates a new String
String s = "Java";
s.concat(" Language");
System.out.println(s);
Output:
Java
Why?
Because concat() creates a new String, but we didnโt store it.
Correct way:
s = s.concat(" Language");
System.out.println(s);
length() Method
Returns the number of characters in a string.
String name = "Ajay";
System.out.println(name.length());
Output:
4
๐ Important:
length()is a method- For arrays, we use
length(without parentheses)
โ Common confusion:
name.length; // โ error
charAt() Method
Returns the character at a given index.
String word = "Java";
System.out.println(word.charAt(0));
System.out.println(word.charAt(2));
Output:
J
v
๐ Index starts from 0.
โ Common mistake:
word.charAt(4); // โ StringIndexOutOfBoundsException
toUpperCase() and toLowerCase()
Used to change case.
String text = "Java Programming";
System.out.println(text.toUpperCase());
System.out.println(text.toLowerCase());
Output:
JAVA PROGRAMMING
java programming
โ ๏ธ Original string remains unchanged.
trim() Method
Removes leading and trailing spaces.
String input = " Java ";
System.out.println(input.trim());
Output:
Java
๐ Does NOT remove spaces between words.
equals() Method
Used to compare content of two strings.
String a = "Java";
String b = "Java";
System.out.println(a.equals(b));
Output:
true
โ
Always use equals() for content comparison.
Common Mistake: == vs equals()
String a = new String("Java");
String b = new String("Java");
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
Explanation:
==compares memory referencesequals()compares actual content
equalsIgnoreCase()
Ignores case while comparing.
String a = "java";
String b = "JAVA";
System.out.println(a.equalsIgnoreCase(b));
Output:
true
contains() Method
Checks if a string contains a sequence.
String sentence = "Java is powerful";
System.out.println(sentence.contains("Java"));
System.out.println(sentence.contains("python"));
Output:
true
false
๐ Case-sensitive.
startsWith() and endsWith()
String file = "report.pdf";
System.out.println(file.startsWith("rep"));
System.out.println(file.endsWith(".pdf"));
Output:
true
true
Very useful in:
- File handling
- URL validation
- Input checking
indexOf() Method
Returns index of first occurrence.
String text = "Java Programming";
System.out.println(text.indexOf("a"));
System.out.println(text.indexOf("Program"));
Output:
1
5
If not found:
System.out.println(text.indexOf("Python")); // -1
lastIndexOf() Method
Returns index of last occurrence.
String text = "banana";
System.out.println(text.lastIndexOf("a"));
Output:
5
substring() Method
Extracts part of a string.
String word = "Programming";
System.out.println(word.substring(0, 7));
Output:
Program
๐ End index is exclusive.
Another example:
System.out.println(word.substring(3));
Output:
gramming
replace() Method
Replaces characters or words.
String msg = "Java is hard";
System.out.println(msg.replace("hard", "easy"));
Output:
Java is easy
๐ Creates a new string.
isEmpty() Method
Checks if string length is 0.
String s = "";
System.out.println(s.isEmpty());
Output:
true
isEmpty() vs null Confusion โ ๏ธ
String s = null;
s.isEmpty(); // โ NullPointerException
Correct check:
if (s != null && !s.isEmpty()) {
System.out.println("Valid string");
}
isBlank() Method (Java 11+)
Checks if string is empty or contains only spaces.
String s = " ";
System.out.println(s.isBlank());
Output:
true
Difference:
isEmpty()โ length = 0isBlank()โ spaces allowed
split() Method
Splits a string into an array.
String line = "Java,Python,C++";
String[] langs = line.split(",");
for (String lang : langs) {
System.out.println(lang);
}
Output:
Java
Python
C++
๐ Very useful for CSV data.
valueOf() Method
Converts other data types into String.
int num = 100;
String s = String.valueOf(num);
System.out.println(s);
Output:
100
compareTo() Method
Used for lexicographical comparison.
String a = "Apple";
String b = "Banana";
System.out.println(a.compareTo(b));
Output:
negative number
Meaning:
0โ equal- Negative โ first comes before
- Positive โ first comes after
Common String Errors & Mistakes ๐ซ
- Forgetting immutability
- Using
==instead ofequals() - Calling methods on
null - Confusing
lengthandlength() - Ignoring case sensitivity
- Assuming methods modify original string
Quick String Methods Summary ๐
length()โ sizecharAt()โ character accessequals()โ content comparisonsubstring()โ extractreplace()โ replace contentsplit()โ convert to arraytrim()โ remove spacescontains()โ searchisEmpty()/isBlank()โ validation
