String Methods in Java
Introduction
Strings are one of the most commonly used classes in Java. The String class provides various methods to manipulate and retrieve information about strings.
1. Common String Methods
- length(): Returns the length of the string.
- substring(): Extracts a portion of the string.
- equals(): Compares the content of two strings.
- toUpperCase(): Converts all characters to uppercase.
- toLowerCase(): Converts all characters to lowercase.
- charAt(): Returns the character at a specified index.
- replace(): Replaces characters or substrings within the string.
- trim(): Removes leading and trailing spaces.
2. Examples
Example 1: Using length()
public class StringLengthExample { public static void main(String[] args) { String str = "Hello World"; System.out.println("Length of the string: " + str.length()); } }
Example 2: Using substring()
public class SubstringExample { public static void main(String[] args) { String str = "Hello World"; String subStr = str.substring(0, 5); System.out.println("Substring: " + subStr); // Output: Hello } }
Example 3: Using equals()
public class EqualsExample { public static void main(String[] args) { String str1 = "Java"; String str2 = "Java"; String str3 = "java"; System.out.println(str1.equals(str2)); // Output: true System.out.println(str1.equals(str3)); // Output: false } }
Example 4: Using toUpperCase() and toLowerCase()
public class CaseConversionExample { public static void main(String[] args) { String str = "Java Programming"; System.out.println("Uppercase: " + str.toUpperCase()); System.out.println("Lowercase: " + str.toLowerCase()); } }
Example 5: Using charAt()
public class CharAtExample { public static void main(String[] args) { String str = "Java"; char ch = str.charAt(2); System.out.println("Character at index 2: " + ch); // Output: v } }
Example 6: Using replace()
public class ReplaceExample { public static void main(String[] args) { String str = "Hello World"; String replacedStr = str.replace("World", "Java"); System.out.println("Replaced String: " + replacedStr); // Output: Hello Java } }
Example 7: Using trim()
public class TrimExample { public static void main(String[] args) { String str = " Hello World "; System.out.println("Trimmed String: " + str.trim()); // Output: Hello World } }
3. Conclusion
The String class in Java provides a wide range of methods for string manipulation. Understanding and using these methods effectively can make string handling more efficient and concise.