String class (java.lang.String) represents character strings. All string literals in Java programs, such as abc, are implemented as instances of this class. String objects are immutable, their values cannot be changed after they are created. StringBuilder class support mutable strings.
Below is the syntax for creating String
String str = "abc"; char data[] = {'a', 'b', 'c'}; String str = new String(data);
Important String API
Change case of string
String toLowerCase()
Converts all of the characters in this string to lower case using the rules of the default locale.String toUpperCase()
Converts all of the characters in this string to upper case using the rules of the default locale.
Substring of String
public String substring(int beginIndex)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndexpublic String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex – 1. Length of the substring is endIndex-beginIndex.
String Matching
public int compareTo(String anotherString)
Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. Result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal.public boolean contains(CharSequence s)
Returns true if and only if this string contains the specified sequence of char values.
Character Manipulation
public int indexOf (int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.public char charAt(int index)
Returns the char value at the specified index. An index ranges from 0 to length() – 1.public char[] toCharArray()
Converts this string to a new character array.
String Length
public boolean isEmpty()
Returns true if, and only if, length() is 0.public int length()
Returns the length of this string. The length is equal to the number of Unicode code units in the string.
String Manipulation
String replace(char oldChar, char newChar)
Returns a string resulting from replacing all occurrences of oldChar in this string with newChar.String replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.String replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement.String[] split(String regex)
Splits this string around matches of the given regular expression.String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.