String Class Methods in Java

In Java, a String is an object that represents a sequence of characters. It’s a fundamental data type used for handling text. Strings in Java are implemented as built-in objects, offering a wide range of features for conveniently manipulating text data.

What is String Class in Java?

In the world of Java programming language, a “String” is like a container that holds a sequence of characters. These characters can be letters, numbers, punctuation marks, or spaces. Strings are widely used for storing and manipulating textual data within Java programs.

String Class Methods in Java

The String class in Java is a versatile and fundamental component for working with text and character sequences. The main reason to make String Class in Java more powerful is the numerous methods that help manipulate strings.

These methods enable developers to perform various operations on strings, from simple tasks like comparing and searching to more complex tasks like modifying and formatting text. In this exploration of String class methods in Java, we will try to understand the String class methods that empower developers to handle and transform textual data within their Java programs efficiently.

Whether you’re a beginner or an experienced Java developer, understanding these methods is key to becoming proficient in text manipulation and string processing in the Java programming language.

Method SignatureDescription
charAt(int index)Returns the character at the specified index within the string.
codePointAt(int index)Returns the Unicode code point at the specified index within the string.
codePointBefore(int index)Returns the Unicode code point before the specified index within the string.
codePointCount(int beginIndex, int endIndex)Returns the number of Unicode code points in the specified range of the string.
compareTo(String anotherString)Compares two strings lexicographically and returns an integer indicating their relative order.
compareToIgnoreCase(String str)Compares two strings lexicographically, ignoring case differences, and returns an integer indicating their relative order.
concat(String str)Concatenates the specified string “str” at the end of the string.
contains(CharSequence sequence)Check if the string ends with the specified suffix.
contentEquals(CharSequence cs)Check if the string contains the specified character sequence.
endsWith(String suffix)Check if the string is empty (has a length of 0).
equals(Object anObject)Check if the string ends with the specified suffix.
equalsIgnoreCase(String anotherString)Compares the string to another string, ignoring case differences.
getBytes() [Deprecated]Encodes the string into a byte array using the platform’s default character encoding.
getBytes(String charsetName)Encodes the string into a byte array using the specified character encoding.
hashCode() It returns the hash code of the string.
indexOf(int ch)Returns the index of the first occurrence of the specified character, or -1 if not found.
indexOf(int ch, int fromIndex)Returns the index of the first occurrence of the specified character, starting the search from fromIndex.
indexOf(String str)Returns the index of the first occurrence of the specified substring, or -1 if not found.
indexOf(String str, int fromIndex)Returns the index of the first occurrence of the specified substring, starting the search from fromIndex.
isEmpty()Check if the entire string matches the given regular expression (regex).
lastIndexOf(int ch)Returns the index of the last occurrence of the specified character, or -1 if not found.
lastIndexOf(int ch, int fromIndex)Returns the index of the last occurrence of the specified character, searching backward from fromIndex.
lastIndexOf(String str)Returns the index of the last occurrence of the specified substring, or -1 if not found.
lastIndexOf(String str, int fromIndex)Returns the index of the last occurrence of the specified substring, searching backward from fromIndex.
length()Returns the length (number of characters) of the string.
matches(String regex)Check if the entire string matches the given regular expression (regex).
replace(char oldChar, char newChar)Check if the entire string matches the given regular expression (regex).
replace(CharSequence target, CharSequence replacement)Replace all occurrences of oldChar with newChar in the string.
replaceAll(String regex, String replacement)Replaces all substrings that match the given regular expression (regex) with the specified replacement string.
replaceFirst(String regex, String replacement)Replaces the first occurrence of a substring that matches the given regular expression (regex) with the specified replacement string.
split(String regex)Splits the string into an array of substrings based on the specified regular expression (regex) as a delimiter.
startsWith(String prefix)Check if the string starts with the specified prefix.
substring(int beginIndex)Returns a new string that is a substring of the original, starting from the specified index.
substring(int beginIndex, int endIndex)Returns a new string that is a substring of the original, starting from beginIndex and ending at endIndex – 1.
toCharArray()Converts the string to a character array.
toLowerCase()Converts all characters in the string to lowercase.
toUpperCase()Converts all characters in the string to uppercase.
trim()Removes leading and trailing white spaces from the string.
valueOf(dataType data) (Static method)Converts data types (int, double, etc.) into a string representation.
Other Methods:

Here are some of the other methods of String Class

chars()Returns a stream of int zero-extending the char values from this sequence.
codePoints()Returns a stream of code point values from this sequence.
contentEquals(StringBuffer sb)Compares this string to the specified StringBuffer.
copyValueOf(char[] data)Equivalent to valueOf(char[]).
copyValueOf(char[] data, int offset, int count)Equivalent to valueOf(char[], int, int).
describeConstable()Returns an Optional containing the nominal descriptor for this instance, which is the instance itself.
format(String format, Object… args)Returns a formatted string using the specified format string and arguments.
format(Locale l, String format, Object… args)Returns a formatted string using the specified locale, format string, and arguments.
formatted(Object… args)Formats using this string as the format string and the supplied arguments.
getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)
Deprecated.
This method does not properly convert characters into bytes.
getBytes(Charset charset)Encodes this String into a sequence of bytes using the given charset, storing the result into a new array.
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)Copies characters from this string into the destination character array.
indent(int n)Adjusts the indentation of each line of this string based on the value of n and normalizes line termination characters.
intern()Returns a canonical representation for the string object.
isBlank()Converts all of the characters in this String to lowercase using the rules of the given Locale.
join(CharSequence delimiter, CharSequence… elements)Returns a new String composed of copies of the CharSequence elements and a copy of the specified delimiter.
join(CharSequence delimiter, Iterable elements)regionMatches(int toffset, String other, int offset, int len)
lines()Returns a stream of lines extracted from this string, separated by line terminators.
offsetByCodePoints(int index, int codePointOffset)Returns the index within this String that is offset from the given index by codePointOffset code points.
regionMatches(boolean ignoreCase, int offset, String other, int offset, int len)Tests if two string regions are equal.
regionMatches(int offset, String other, int offset, int len)Tests if two string regions are equal.
repeat(int count)Returns a string whose value is the concatenation of this string repeated count times.
resolveConstantDesc(MethodHandles.Lookup lookup)startsWith(String prefix, int offset)
split(String regex, int limit)Splits this string around matches of the given regular expression.
regionMatches(int offset, String other, int offset, int len)Tests if the substring of this string beginning at the specified index starts with the specified prefix.
strip()Returns a string whose value is this string, with all leading and trailing white space removed.
stripIndent()Returns a string whose value is this string, with incidental white space removed from the beginning and end of every line.
stripLeading()Returns a string whose value is this string, with all leading white space removed.
stripTrailing()Returns a string whose value is this string, with all trailing white space removed.
subSequence(int beginIndex, int endIndex)Returns a character sequence that is a subsequence of this sequence.
toLowerCase(Locale locale)Formats using this string as the format string and the supplied arguments.
toString()This object (which is already a string!)
toUpperCase(Locale locale)Converts all of the characters in this String to upper case using the rules of the given Locale.
transform(Function f)This method allows the application of a function to this string.
translateEscapes()Returns a string whose value is this string, with escape sequences translated as if in a string literal.
valueOf(boolean b)Returns the string representation of the boolean argument.
valueOf(char c)Returns the string representation of the char argument.
valueOf(char[] data)Returns the string representation of the char array argument.
valueOf(char[] data, int offset, int count)Returns the string representation of a specific subarray of the char array argument.
valueOf(double d)Returns the string representation of the double argument.
valueOf(float f)Returns the string representation of the float argument.
valueOf(int i)Returns the string representation of the int argument.
valueOf(long l)Returns the string representation of the long argument.
valueOf(Object obj)Returns the string representation of the Object argument.

Conclusion

Understanding the various methods in the “String” class is important for effective string manipulation and text processing in Java. We’ve covered many methods, from the foundational ones introduced in Java 1.0 to the recent additions in Java.

These methods empower Java developers to work with strings efficiently, whether for basic operations like comparison and concatenation or more advanced tasks involving Unicode, white space handling, and regular expressions.

If you have any doubts or questions about the “String Class Methods in Java,” please don’t hesitate to comment below. Your feedback is valuable, and if you have any suggestions to improve this article or topics you’d like to see covered in the future, we welcome your input in the comment section. Your engagement helps us create content that addresses your specific needs and interests. Thank you for reading, and we look forward to your comments!

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment