String Class
The String class in Java is used to represent a sequence of characters. It is an immutable class, which means that once a string is created, its value cannot be changed. The class provides a number of useful methods to perform various operations on strings. Here are some common methods of the String class:
length(): Returns the length of the string.
charAt(int index): Returns the character at the specified index.
substring(int beginIndex, int endIndex): Returns a new string that is a substring of this string.
concat(String str): Concatenates the specified string to the end of this string.
equals(Object obj): Compares this string to the specified object for equality.
compareTo(String anotherString): Compares this string to another string.
toLowerCase(): Converts all of the characters in this string to lower case.
toUpperCase(): Converts all of the characters in this string to upper case.
trim(): Returns a new string that is a copy of this string with leading and trailing white space removed.
indexOf(int ch): Returns the index within this string of the first occurrence of the specified character.
lastIndexOf(int ch): Returns the index within this string of the last occurrence of the specified character.
contains(CharSequence s): Returns true if this string contains the specified sequence of char values.
replace(char oldChar, char newChar): Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
startsWith(String prefix): Tests if this string starts with the specified prefix.
endsWith(String suffix): Tests if this string ends with the specified suffix.
String class example in Java
refer to:theitroad.compublic class StringExample {
public static void main(String[] args) {
// Create a String object
String str = "Hello, World!";
System.out.println("String is: " + str);
// Get the length of the string
int length = str.length();
System.out.println("Length of the string is: " + length);
// Convert the string to uppercase
String upperCase = str.toUpperCase();
System.out.println("Uppercase string is: " + upperCase);
// Convert the string to lowercase
String lowerCase = str.toLowerCase();
System.out.println("Lowercase string is: " + lowerCase);
// Check if the string contains a particular substring
boolean contains = str.contains("World");
System.out.println("Does the string contain 'World'? " + contains);
// Replace a substring in the string with another substring
String replaced = str.replace("World", "Java");
System.out.println("Replaced string is: " + replaced);
}
}
