Java Strings Class

java

In Java, the java.lang.String class represents a sequence of characters. Strings are immutable, which means that once a string is created, it cannot be modified. Instead, any operations that would modify a string will create a new string object.

Here are some common methods of the String class:

int length(): Returns the length of the string.
char charAt(int index): Returns the character at the specified index.
int indexOf(String str): Returns the index of the first occurrence of the specified string, or -1 if the string is not found.
int lastIndexOf(String str): Returns the index of the last occurrence of the specified string, or -1 if the string is not found.
String substring(int beginIndex): Returns a new string that is a substring of this string, starting at the specified index.
String substring(int beginIndex, int endIndex): Returns a new string that is a substring of this string, starting at the specified index and ending at the specified index.
String replace(char oldChar, char newChar): Returns a new string with all occurrences of the specified character replaced with the specified character.
String trim(): Returns a new string with leading and trailing whitespace removed.

Here is an example of how to use the String class:

String s = "Hello, World!";

int len = s.length(); // len is 13
char c = s.charAt(0); // c is 'H'
int i = s.indexOf("World"); // i is 7
int j = s.lastIndexOf("l"); // j is 9
String t = s.substring(7); // t is "World!"
String u = s.substring(7, 12); // u is "World"
String v = s.replace('l', 'L'); // v is "HeLLo, WorLd!"
String w = s.trim(); // w is "Hello, World!"