Java Strings Class: Creating and Manipulating Strings in Java
Learn about the String
class in Java, which is used to create and manipulate strings, a sequence of characters. Explore the various methods provided by the Java platform to handle string operations effectively.
Java Strings Class
Strings, widely used in Java programming, are a sequence of characters. In Java, strings are treated as objects. The Java platform provides the String class to create and manipulate strings.
Creating Strings
The most direct way to create a string is:
String greeting = "Hello world!";
Whenever a string literal is encountered in the code, the compiler creates a String object with its value. You can also create String objects using the new keyword and a constructor. The String class has 11 constructors that allow you to provide the initial value of the string using different sources, such as an array of characters.
Creating String from Char Array Example
public class StringDemo {
public static void main(String args[]) {
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println(helloString);
}
}
Output
hello.
Note: The String class is immutable, so once a String object is created, it cannot be changed. For many modifications to strings, use StringBuffer or StringBuilder classes.
String Length
Methods used to obtain information about an object are known as accessor methods. One such method for strings is the length()
method, which returns the number of characters contained in the string object.
Getting Length of the String Example
public class StringDemo {
public static void main(String args[]) {
String palindrome = "Don saw I was Tom";
int len = palindrome.length();
System.out.println("String Length is: " + len);
}
}
Output
String Length is: 17
Concatenating Strings
The String class includes a method for concatenating two strings:
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also use the concat()
method with string literals:
"My name is ".concat("Zara");
Strings are more commonly concatenated with the +
operator:
"Hello," + " world" + "!";
which results in:
"Hello, world!"
Concatenating String Example
public class StringDemo {
public static void main(String args[]) {
String string1 = "saw I was ";
System.out.println("Don " + string1 + "Tom");
}
}
Output
Don saw I was Tom
Creating Formatted Strings
You can use the printf()
and format()
methods to print output with formatted numbers. The String class has a static format()
method that returns a String object rather than a PrintStream object.
Formatted String Example
System.out.printf("The value of the float variable is %f, while the value of the integer variable is %d, and the string is %s", floatVar, intVar, stringVar);
String fs;
fs = String.format("The value of the float variable is %f, while the value of the integer variable is %d, and the string is %s", floatVar, intVar, stringVar);
String Methods
Here is the list of methods supported by the String class:
char charAt(int index)
- Returns the char value at the specified index.int codePointAt(int index)
- Returns the character (Unicode code point) at the specified index.int codePointBefore(int index)
- Returns the character (Unicode code point) before the specified index.int codePointCount(int beginIndex, int endIndex)
- Returns the number of Unicode code points in the specified text range of this String.int compareTo(String anotherString)
- Compares two strings lexicographically.int compareToIgnoreCase(String str)
- Compares two strings lexicographically, ignoring case differences.String concat(String str)
- Concatenates the specified string to the end of this string.boolean contains(CharSequence s)
- Returns true if this string contains the specified sequence of char values.boolean contentEquals(CharSequence cs)
- Compares this string to the specified CharSequence.static String copyValueOf(char[] data)
- Returns a String representing the character sequence in the array specified.boolean endsWith(String suffix)
- Tests if this string ends with the specified suffix.boolean equals(Object anObject)
- Compares this string to the specified object.boolean equalsIgnoreCase(String anotherString)
- Compares this String to another String, ignoring case considerations.static String format(String format, Object... args)
- Returns a formatted string using the specified format string and arguments.byte[] getBytes()
- Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
- Copies characters from this string into the destination character array.int hashCode()
- Returns a hash code for this string.int indexOf(int ch)
- Returns the index within this string of the first occurrence of the specified character.String intern()
- Returns a canonical representation for the string object.boolean isEmpty()
- Returns true if, and only if, length() is 0.int lastIndexOf(int ch)
- Returns the index within this string of the last occurrence of the specified character.int length()
- Returns the length of this string.boolean matches(String regex)
- Tells whether or not this string matches the given regular expression.int offsetByCodePoints(int index, int codePointOffset)
- Returns the index within this String that is offset from the given index by codePointOffset code points.boolean regionMatches(int toffset, String other, int ooffset, int len)
- Tests if two string regions are equal.String replace(char oldChar, char newChar)
- Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.String replaceAll(String regex, String replacement)
- Replaces each substring of this string that matches the given regular expression with the given replacement.String replaceFirst(String regex, String replacement)
- Replaces the first 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.boolean startsWith(String prefix)
- Tests if this string starts with the specified prefix.CharSequence subSequence(int beginIndex, int endIndex)
- Returns a new character sequence that is a subsequence of this sequence.String substring(int beginIndex)
- Returns a new string that is a substring of this string.char[] toCharArray()
- Converts this string to a new character array.String toLowerCase()
- Converts all of the characters in this String to lower case using the rules of the default locale.String toString()
- Returns the string itself.String toUpperCase()
- Converts all of the characters in this String to upper case using the rules of the default locale.String trim()
- Returns a copy of the string, with leading and trailing whitespace omitted.static String valueOf(boolean b)
- Returns the string representation of the boolean argument.