String Class in Java

Definition: String is sequence of Characters.

The String class with method provides many operations can be performed on strings such as convert the string to character array, convert numbers into strings, search strings, create substrings, change of the case of the string, get a string’s length, compare strings, and much more.

Strings can be declared and creates as follows:

String str;
str = new String(“Hello from Java!”)

Example:

/**
 *
 * @author JavaHotSpot
 */

public class stringExample
{
        public static void main(String args[])
                        {
                                        String str = new String(“Hello from Java!”);
                                        System.out.println(str);
                        }
}

String class methods:

The String class provides a number of methods that allows user to accomplish many numbers of string manipulation tasks. The following tables demonstrate the most commonly used string methods.


Method
Meaning
1
char charAt(int index)
Returns the character at the given index.
2
int compareTo(String str)
Returns zero if two strings are matched.
3
String concat(String str)
Returns concatenation of two strings.
4
byte[] getBytes()
Converts string into byte and stores the result in a new byte array.
5
Int indexOf(int x)
Returns the position of the first occurrence of the given character.
6
Int length()
Returns length of string.
7
String replace(char old, char new)
Replace old character with new character.
8
boolean startsWith(String prefix)

Check whether the string starts with given prefix.
9
String substring(int startIndex)
Returns substring starting from start Index.
10
String substring(int start, int end)
Returns substring starting from start   index up to end index.
11
Char[] toCharArray()
Converts the string into character array.
12
String toLowerCase()
Converts all the characters in the string to lower case.
13
String toUpperCase()
Converts all the characters in the string to upper case.
14
String trim()
Removes white spaces from the both ends of the string.
15
String equals(String str)
Returns true if both strings are equal