Java String Methods with Examples
length()
Returns the length of the string.
Example:
String str = "Hello";
[Link]([Link]()); // Output: 5
charAt(int index)
Returns the character at the specified index.
Example:
String str = "Hello";
[Link]([Link](1)); // Output: e
substring(int beginIndex, int endIndex)
Returns a substring from the string.
Example:
String str = "Hello World";
[Link]([Link](0, 5)); // Output: Hello
equals(String anotherString)
Compares two strings for equality.
Example:
String a = "Java";
String b = "Java";
[Link]([Link](b)); // Output: true
equalsIgnoreCase(String anotherString)
Compares two strings, ignoring case.
Example:
String a = "Java";
String b = "java";
[Link]([Link](b)); // Output: true
toLowerCase() / toUpperCase()
Converts string to lowercase or uppercase.
Example:
String str = "Java";
[Link]([Link]()); // java
[Link]([Link]()); // JAVA
trim()
Removes leading and trailing spaces.
Example:
String str = " Hello ";
[Link]([Link]()); // Hello
contains(CharSequence s)
Checks if string contains a sequence.
Example:
String str = "Welcome";
[Link]([Link]("come")); // true
replace(char oldChar, char newChar)
Replaces characters in the string.
Example:
String str = "banana";
[Link]([Link]('a', 'o')); // bonono
split(String regex)
Splits the string based on regex.
Example:
String str = "apple,banana,mango";
String[] fruits = [Link](",");
for(String fruit : fruits){ [Link](fruit); }
indexOf(String str)
Returns the index of first occurrence.
Example:
String str = "hello";
[Link]([Link]("l")); // 2
isEmpty()
Checks if the string is empty.
Example:
String str = "";
[Link]([Link]()); // true
startsWith(String prefix) / endsWith(String suffix)
Checks if string starts/ends with something.
Example:
String str = "programming";
[Link]([Link]("pro")); // true
[Link]([Link]("ing")); // true
compareTo(String anotherString)
Compares strings lexicographically.
Example:
String a = "abc";
String b = "abd";
[Link]([Link](b)); // -1
concat(String str)
Concatenates two strings.
Example:
String a = "Hello ";
String b = "World";
[Link]([Link](b)); // Hello World
valueOf(int i)
Converts other types to string.
Example:
int num = 123;
String str = [Link](num);
[Link](str); // "123"