String Methods in Java
Java provides various methods to manipulate and process strings using the
String class. Here are some commonly used String methods:
1. String Length
length() → Returns the length of the string.
String str = "Hello World";
[Link]([Link]()); // Output: 11
2. Case Conversion
toUpperCase() → Converts the string to uppercase.
toLowerCase() → Converts the string to lowercase.
String str = "Java";
[Link]([Link]()); // Output: JAVA
[Link]([Link]()); // Output: java
3. Character Extraction
charAt(index) → Returns the character at the specified index.
String str = "Java";
[Link]([Link](1)); // Output: a
4. Substring Extraction
substring(startIndex) → Extracts substring from the given index to the
end.
substring(startIndex, endIndex) → Extracts substring between given
indexes.
String str = "Hello World";
[Link]([Link](6)); // Output: World
[Link]([Link](0, 5)); // Output: Hello
5. String Comparison
equals(str) → Checks if two strings are equal.
equalsIgnoreCase(str) → Checks equality ignoring case.
compareTo(str) → Compares two strings lexicographically.
String str1 = "Java";
String str2 = "java";
[Link]([Link](str2)); // Output: false
[Link]([Link](str2)); // Output: true
[Link]([Link]("Javb")); // Output: -1
How it Works:
[Link](string2) returns:
o 0 if both strings are equal
o A positive value if string1 is greater than string2
o A negative value if string1 is less than string2
6. String Search
indexOf(char/substring) → Returns the index of the first occurrence.
lastIndexOf(char/substring) → Returns the last occurrence index.
contains(str) → Checks if string contains a substring.
startsWith(str) → Checks if string starts with a given substring.
endsWith(str) → Checks if string ends with a given substring.
String str = "Hello World";
[Link]([Link]('o')); // Output: 4
[Link]([Link]('o')); // Output: 7
[Link]([Link]("World")); // Output: true
[Link]([Link]("Hello")); // Output: true
[Link]([Link]("World")); // Output: true
7. String Modification
replace(oldChar, newChar) → Replaces all occurrences of a character.
replaceAll(regex, replacement) → Replaces all substrings matching a
regex.
trim() → Removes leading and trailing spaces.
String str = " Java Programming ";
[Link]([Link]()); // Output: "Java Programming"
[Link]([Link]('a', '@')); // Output: J@v@ Progr@mming
[Link]([Link]("[aA]", "#"));
[Link]("123abc".replaceAll("[0-9]", "*")); // Output: ***abc
8. Splitting and Joining
split(delimiter) → Splits string into an array based on a delimiter.
join(delimiter, elements…) → Joins multiple elements into a single
string.
String str = "apple,banana,grape";
String[] fruits = [Link](",");
for (String fruit : fruits) {
[Link](fruit);
}
// Output: apple
// banana
// grape
String joined = [Link](" - ", "Java", "Python", "C++");
[Link](joined); // Output: Java - Python - C++
9. String Concatenation
concat(str) → Concatenates two strings.
String str1 = "Hello";
String str2 = "World";
[Link]([Link](" " + str2)); // Output: Hello World
10. String Conversion
valueOf(data) → Converts different data types to a string.
int num = 100;
String str = [Link](num);
[Link](str + 10); // Output: 10010
11. Checking if String is Empty or Blank
isEmpty() → Returns true if the string is empty ("").
isBlank() → Returns true if the string is empty or contains only white
spaces.
String str1 = "";
String str2 = " ";
[Link]([Link]()); // Output: true
[Link]([Link]()); // Output: true
12. Interning a String
intern() → Returns the canonical representation of the string from the
string pool.
String str1 = new String("Java");
String str2 = [Link]();
[Link](str1 == str2); // Output: false
[Link](str2 == "Java"); // Output: true
Why use intern()?
To save memory when you have many strings with the same content.
Useful when comparing strings using == instead of .equals().
13. Checking String Content
matches(regex) → Checks if string matches a regular expression.
String str = "Java123";
[Link]([Link]("[A-Za-z0-9]+")); // Output: true
[Link]([Link]("\\d+")); // Output: false
14. Removing Characters
replaceFirst(regex, replacement) → Replaces the first occurrence
matching the regex.
String str = "Java is fun, Java is powerful";
[Link]([Link]("Java", "Python"));
// Output: Python is fun, Java is powerful
15. Getting Bytes and Characters
getBytes() → Converts string into a byte array.
toCharArray() → Converts string into a character array.
String str = "Hello";
byte[] byteArray = [Link]();
char[] charArray = [Link]();
[Link]([Link](byteArray)); // Output: [72, 101, 108, 108,
111]
[Link]([Link](charArray)); // Output: [H, e, l, l, o]
16. Formatting a String
format(format, args…) → Returns a formatted string.
String name = "aaa";
int age = 25;
String formatted = [Link]("Name: %s, Age: %d", name, age);
[Link](formatted);
// Output: Name: aaa, Age: 25
17. String Joining with Multiple Values
join() → Joins multiple strings with a delimiter.
String result = [Link]("-", "Java", "Python", "C++");
[Link](result); // Output: Java-Python-C++
18. Converting String to Numeric Values
[Link](str) → Converts a string to an integer.
[Link](str) → Converts a string to a double.
String str = "100";
int num = [Link](str);
double dnum = [Link]("99.99");
[Link](num + 1); // Output: 101
[Link](dnum + 0.01); // Output: 100.0
19. Checking if Two Strings are Equal (Content Comparison)
contentEquals(StringBuffer/StringBuilder) → Compares string
content.
String str1 = "Hello";
StringBuffer str2 = new StringBuffer("Hello");
[Link]([Link](str2)); // Output: true
20. Using regionMatches()
regionMatches(start1, str2, start2, length) → Compares a region of
two strings.
String str1 = "JavaProgramming";
String str2 = "Programming";
[Link]([Link](4, str2, 0, 11)); // Output: true
21. Checking a String's Code Points
codePointAt(index) → Returns the Unicode value at the given index.
codePointBefore(index) → Returns the Unicode value before the given
index.
codePointCount(beginIndex, endIndex) → Returns the count of
Unicode points in a substring.
String str = "Hello";
[Link]([Link](0)); // Output: 72 ('H')
[Link]([Link](1)); // Output: 72 ('H')
[Link]([Link](0, 5)); // Output: 5
22. Checking Character Types
isUpperCase() / isLowerCase() → Checks if characters are
uppercase/lowercase.
char ch = 'A';
[Link]([Link](ch)); // Output: true
[Link]([Link](ch)); // Output: false
23. Escaping Special Characters
Use escape sequences in strings:
String str = "She said, \"Java is awesome!\"";
[Link](str); // Output: She said, "Java is awesome!"
24. String Builder vs. String Buffer
StringBuffer and StringBuilder are mutable versions of String.
StringBuilder sb = new StringBuilder("Java");
[Link](" Rocks!");
[Link](sb); // Output: Java Rocks!
25. Checking Whether a String is Numeric
Use matches() to check if a string is numeric.
String str = "12345";
[Link]([Link]("\\d+")); // Output: true
Feature String StringBuilder
Immutable (value
Mutability Mutable (value can be modified)
cannot be changed)
Slower for repeated
Performance Faster for repeated modifications
modifications
Creates new object for
Memory usage Changes occur in the same object
every change
Thread-safe (due to
Thread-safety Not thread-safe
immutability)
Use case Best for constant or Best for dynamic string operations
Feature String StringBuilder
rarely changing text
Package [Link] [Link]
Methods for Methods like concat() Methods like append(), insert(), etc.,
modification return new object modify in place
StringBuilder sb = new
String s = "Hello"; s +=
Example StringBuilder("Hello");
"World";
[Link]("World");