Java Strings and String Methods - Complete Guide
Strings in Java - Complete Guide with Examples
What is a String?
A String in Java is a sequence of characters. It is an object of the String class in the [Link]
package.
Example:
String name = "Java";
Creating Strings
1. Using String Literal
String str1 = "Hello";
2. Using new Keyword
String str2 = new String("Hello");
String Methods with Examples
1. length()
Returns the number of characters in the string.
Example:
String name = "Java Programming";
[Link]("Length: " + [Link]());
2. charAt(int index)
Returns the character at the specified index.
Example:
String word = "Hello";
[Link]("Character at index 1: " + [Link](1));
3. substring(int beginIndex, int endIndex)
Returns a part (substring) of the string.
Example:
String word = "Programming";
[Link]("Substring (0 to 6): " + [Link](0, 6));
4. equals(String another)
Checks whether two strings are equal (case-sensitive).
Example:
String a = "Java";
String b = "Java";
[Link]("Are they equal? " + [Link](b));
5. equalsIgnoreCase(String another)
Checks equality ignoring case.
Example:
String a = "java";
String b = "JAVA";
[Link]("Ignore case equal? " + [Link](b));
6. toLowerCase()
Converts the string to lowercase.
Example:
String msg = "WELCOME";
[Link]("Lowercase: " + [Link]());
7. toUpperCase()
Converts the string to uppercase.
Example:
String msg = "welcome";
[Link]("Uppercase: " + [Link]());
8. contains(CharSequence s)
Checks if the string contains the given sequence.
Example:
String data = "Hello Java";
[Link]("Contains 'Java'? " + [Link]("Java"));
9. indexOf(String str)
Returns the first index of the substring.
Example:
String text = "banana";
[Link]("Index of 'na': " + [Link]("na"));
10. replace(char oldChar, char newChar)
Replaces characters in the string.
Example:
String fruit = "banana";
[Link]("Replaced: " + [Link]('a', 'o'));
11. trim()
Removes leading and trailing spaces.
Example:
String s = " Hello Java ";
[Link]("Before trim: '" + s + "'");
[Link]("After trim: '" + [Link]() + "'");
12. startsWith(String prefix) and endsWith(String suffix)
Checks whether a string starts or ends with a specific string.
Example:
String file = "[Link]";
[Link]("Starts with 'rep'? " + [Link]("rep"));
[Link]("Ends with '.pdf'? " + [Link](".pdf"));
13. isEmpty()
Checks if the string is empty.
Example:
String empty = "";
[Link]("Is string empty? " + [Link]());
14. concat(String str)
Concatenates (joins) two strings.
Example:
String s1 = "Hello";
String s2 = " World";
[Link]("Concatenated: " + [Link](s2));