Introduction
Java's String
class provides a comprehensive set of methods for string manipulation, comparison, searching, and more. Understanding these methods is crucial for effective string handling in Java applications. This cheat sheet lists all the String
methods available in Java SE 22, providing a brief description, examples, and explanations.
Java String Methods Cheat Sheet
Method | Description |
---|---|
charAt(int index) | Returns the character at the specified index. |
codePointAt(int index) | Returns the Unicode code point at the specified index. |
codePointBefore(int index) | Returns the Unicode code point before the specified index. |
codePointCount(int beginIndex, int endIndex) | Returns the number of Unicode code points in the specified text range. |
compareTo(String anotherString) | Compares two strings lexicographically. |
compareToIgnoreCase(String str) | Compares two strings lexicographically, ignoring case differences. |
concat(String str) | Concatenates the specified string to the end of this string. |
contains(CharSequence s) | Returns true if this string contains the specified sequence of char values. |
contentEquals(CharSequence cs) | Compares this string to the specified CharSequence. |
copyValueOf(char[] data) | Returns a String that represents the character sequence in the array. |
endsWith(String suffix) | Tests if this string ends with the specified suffix. |
equals(Object anObject) | Compares this string to the specified object. |
equalsIgnoreCase(String anotherString) | Compares this String to another String, ignoring case considerations. |
format(String format, Object... args) | Returns a formatted string using the specified format string and arguments. |
getBytes() | Encodes this String into a sequence of bytes using the platform's default charset. |
getBytes(String charsetName) | Encodes this String into a sequence of bytes using the named charset. |
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) | Copies characters from this string into the destination character array. |
hashCode() | Returns a hash code for this string. |
indexOf(int ch) | Returns the index within this string of the first occurrence of the specified character. |
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. |
indexOf(String str) | Returns the index within this string of the first occurrence of the specified substring. |
indexOf(String str, int fromIndex) | Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. |
intern() | Returns a canonical representation for the string object. |
isBlank() | Returns true if the string is empty or contains only white space codepoints. |
isEmpty() | Returns true if, and only if, length() is 0. |
join(CharSequence delimiter, CharSequence... elements) | Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter. |
lastIndexOf(int ch) | Returns the index within this string of the last occurrence of the specified character. |
lastIndexOf(int ch, int fromIndex) | Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index. |
lastIndexOf(String str) | Returns the index within this string of the last occurrence of the specified substring. |
lastIndexOf(String str, int fromIndex) | Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index. |
length() | Returns the length of this string. |
lines() | Returns a stream of lines extracted from this string, separated by line terminators. |
matches(String regex) | Tells whether or not this string matches the given regular expression. |
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 toffset, String other, int ooffset, 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. |
replace(char oldChar, char newChar) | Returns a string resulting from replacing all occurrences of oldChar in this string with newChar. |
replace(CharSequence target, CharSequence replacement) | Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. |
replaceAll(String regex, String replacement) | Replaces each substring of this string that matches the given regular expression with the given replacement. |
replaceFirst(String regex, String replacement) | Replaces the first substring of this string that matches the given regular expression with the given replacement. |
split(String regex) | Splits this string around matches of the given regular expression. |
split(String regex, int limit) | Splits this string around matches of the given regular expression. |
startsWith(String prefix) | Tests if this string starts with the specified prefix. |
startsWith(String prefix, int toffset) | 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. |
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. |
substring(int beginIndex) | Returns a string that is a substring of this string. |
substring(int beginIndex, int endIndex) | Returns a string that is a substring of this string. |
toCharArray() | Converts this string to a new character array. |
toLowerCase() | Converts all of the characters in this String to lower case using the rules of the default locale. |
toLowerCase(Locale locale) | Converts all of the characters in this String to lower case using the rules of the given Locale. |
toUpperCase() | Converts all of the characters in this String to upper case using the rules of the default locale. |
toUpperCase(Locale locale) | Converts all of the characters in this String to upper case using the rules of the given Locale. |
trim() | Returns a string whose value is this string, with all leading and trailing space removed. |
valueOf(char[] data) | Returns the string representation of the char array argument. |
Explanation and Examples of Java String Methods
charAt(int index)
Returns the character at the specified index.
Example:
String str = "Hello";
char result = str.charAt(1); // e
Explanation: This method returns the character located at index 1 in the string "Hello".
codePointAt(int index)
Returns the Unicode code point at the specified index.
Example:
String str = "Hello";
int codePoint = str.codePointAt(1); // 101
Explanation: This method returns the Unicode code point of the character at index 1 in the string "Hello".
codePointBefore(int index)
Returns the Unicode code point before the specified index.
Example:
String str = "Hello";
int codePoint = str.codePointBefore(1); // 72
Explanation: This method returns the Unicode code point of the character before index 1 in the string "Hello".
codePointCount(int beginIndex, int endIndex)
Returns the number of Unicode code points in the specified text range.
Example:
String str = "Hello";
int codePoints = str.codePointCount(0, 5); // 5
Explanation: This method returns the number of Unicode code points between the specified begin and end indexes.
compareTo(String anotherString)
Compares two strings lexicographically.
Example:
String str1 = "Hello";
String str2 = "World";
int result = str1.compareTo(str2); // negative value
Explanation: This method compares the strings "Hello" and "World" lexicographically.
compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences.
Example:
String str1 = "Hello";
String str2 = "hello";
int result = str1.compareToIgnoreCase(str2); // 0
Explanation: This method compares the strings lexicographically, ignoring case differences.
concat(String str)
Concatenates the specified string to the end of this string.
Example:
String str1 = "Hello";
String str2 = "World";
String result = str1.concat(str2); // HelloWorld
Explanation: This method appends the string str2
to the end of str1
.
contains(CharSequence s)
Returns true
if this string contains the specified sequence of char values.
Example:
String str = "Hello World";
boolean result = str.contains("World"); // true
Explanation: This method checks if the string "Hello World" contains the sequence "World".
contentEquals(CharSequence cs)
Compares this string to the specified CharSequence
.
Example:
String str = "Hello";
StringBuffer sb = new StringBuffer("Hello");
boolean result = str.contentEquals(sb); // true
Explanation: This method compares the string with the StringBuffer
content and returns true
if they are equal.
copyValueOf(char[] data)
Returns a String
that represents the character sequence in the array.
Example:
char[] data = {'H', 'e', 'l', 'l', 'o'};
String str = String.copyValueOf(data); // Hello
Explanation: This method creates a string from the character array data
.
endsWith(String suffix)
Tests if this string ends with the specified suffix.
Example:
String str = "Hello World";
boolean result = str.endsWith("World"); // true
Explanation: This method checks if the string "Hello World" ends with the suffix "World".
equals(Object anObject)
Compares this string to the specified object.
Example:
String str1 = "Hello";
String str2 = "Hello";
boolean result = str1.equals(str2); // true
Explanation: This method compares the string str1
with the object str2
for equality.
equalsIgnoreCase(String anotherString)
Compares this String
to another String
, ignoring case considerations.
Example:
String str1 = "hello";
String str2 = "HELLO";
boolean result = str1.equalsIgnoreCase(str2); // true
Explanation: This method compares the strings str1
and str2
for equality, ignoring case differences.
format(String format, Object... args)
Returns a formatted string using the specified format string and arguments.
Example:
String str = String.format("Name: %s, Age: %d", "John", 30); // Name: John, Age: 30
Explanation: This method formats the string according to the specified format and arguments.
getBytes()
Encodes this String
into a sequence of bytes using the platform's default charset.
Example:
String str = "Hello";
byte[] bytes = str.getBytes();
Explanation: This method converts the string to a byte array using the default charset.
getBytes(String charsetName)
Encodes this String
into a sequence of bytes using the named charset.
Example:
String str = "Hello";
byte[] bytes = str.getBytes("UTF-8");
Explanation: This method converts the string to a byte array using the specified charset "UTF-8".
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
Example:
String str = "Hello World";
char[] dst = new char[5];
str.getChars(0, 5, dst, 0); // dst contains "Hello"
Explanation: This method copies characters from the string to the character array dst
.
hashCode()
Returns a hash code for this string.
Example:
String str = "Hello";
int hash = str.hashCode();
Explanation: This method returns the hash code value for the string.
indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
Example:
String str = "Hello World";
int index = str.indexOf('o'); // 4
Explanation: This method returns the index of the first occurrence of the character 'o' in the string.
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.
Example:
String str = "Hello World";
int index = str.indexOf('o', 5); // 7
Explanation: This method returns the index of the first occurrence of the character 'o' in the string, starting from index 5.
indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
Example:
String str = "Hello World";
int index = str.indexOf("World"); // 6
Explanation: This method returns the index of the first occurrence of the substring "World" in the string.
indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
Example:
String str = "Hello World World";
int index = str.indexOf("World", 7); // 12
Explanation: This method returns the index of the first occurrence of the substring "World" in the string, starting from index 7.
intern()
Returns a canonical representation for the string object.
Example:
String str1 = new String("Hello");
String str2 = str1.intern();
Explanation: This method returns a canonical representation of the string, ensuring that strings with the same content share the same memory.
isBlank()
Returns true
if the string is empty or contains only white space codepoints.
Example:
String str = " ";
boolean result = str.isBlank(); // true
Explanation: This method checks if the string is empty or consists only of white space characters.
isEmpty()
Returns true
if, and only if, length()
is 0.
Example:
String str = "";
boolean result = str.isEmpty(); // true
Explanation: This method checks if the string is empty.
join(CharSequence delimiter, CharSequence... elements)
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
Example:
String result = String.join(", ", "A", "B", "C"); // A, B, C
Explanation: This method joins the elements "A", "B", and "C" with the delimiter ", ".
lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.
Example:
String str = "Hello World";
int index = str.lastIndexOf('o'); // 7
Explanation: This method returns the index of the last occurrence of the character 'o' in the string.
lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
Example:
String str = "Hello World";
int index = str.lastIndexOf('o', 6); // 4
Explanation: This method returns the index of the last occurrence of the character 'o' in the string, searching backward from index 6.
lastIndexOf(String str)
Returns the index within this string of the last occurrence of the specified substring.
Example:
String str = "Hello World World";
int index = str.lastIndexOf("World"); // 12
Explanation: This method returns the index of the last occurrence of the substring "World" in the string.
lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
Example:
String str = "Hello World World";
int index = str.lastIndexOf("World", 11); // 6
Explanation: This method returns the index of the last occurrence of the substring "World" in the string, searching backward from index 11.
length()
Returns the length of this string.
Example:
String str = "Hello";
int length = str.length(); // 5
Explanation: This method returns the length of the string "Hello".
lines()
Returns a stream of lines extracted from this string, separated by line terminators.
Example:
String str = "Hello\nWorld\nJava";
str.lines().forEach(System.out::println);
// Output:
// Hello
// World
// Java
Explanation: This method splits the string into lines based on line terminators and returns a stream of those lines.
matches(String regex)
Tells whether or not this string matches the given regular expression.
Example:
String str = "123-45-6789";
boolean result = str.matches("\\d{3}-\\d{2}-\\d{4}"); // true
Explanation: This method checks if the string "123-45-6789" matches the regular expression for a social security number format.
offsetByCodePoints(int index, int codePointOffset)
Returns the index within this String
that is offset from the given index
by codePointOffset
code points.
Example:
String str = "Hello";
int offsetIndex = str.offsetByCodePoints(0, 2); // 2
Explanation: This method returns the index offset by 2 code points from the beginning of the string.
regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
Example:
String str1 = "Hello World";
String str2 = "WORLD";
boolean result = str1.regionMatches(true, 6, str2, 0, 5); // true
Explanation: This method checks if the region "World" in str1
matches "WORLD" in str2
ignoring case.
repeat(int count)
Returns a string whose value is the concatenation of this string repeated count
times.
Example:
String str = "Hi";
String result = str.repeat(3); // HiHiHi
Explanation: This method repeats the string "Hi" three times.
replace(char oldChar, char newChar)
Returns a string resulting from replacing all occurrences of oldChar
in this string with newChar
.
Example:
String str = "Hello";
String result = str.replace('l', 'p'); // Heppo
Explanation: This method replaces all occurrences of the character 'l' with 'p' in the string.
replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
Example:
String str = "Hello World";
String result = str.replace("World", "Java"); // Hello Java
Explanation: This method replaces the substring "World" with "Java" in the string.
replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement.
Example:
String str = "abc123xyz";
String result = str.replaceAll("\\d", "-"); // abc---xyz
Explanation: This method replaces all digits in the string with hyphens.
replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the given replacement.
Example:
String str = "abc123xyz";
String result = str.replaceFirst("\\d", "-"); // abc-23xyz
Explanation: This method replaces the first digit in the string with a hyphen.
split(String regex)
Splits this string around matches of the given regular expression.
Example:
String str = "one,two,three";
String[] result = str.split(","); // [one, two, three]
Explanation: This method splits the string "one,two,three" into an array of substrings.
split(String regex, int limit)
Splits this string around matches of the given regular expression, with a limit on the number of resulting substrings.
Example:
String str = "one,two,three";
String[] result = str.split(",", 2); // [one, two,three]
Explanation: This method splits the string into at most two substrings.
startsWith(String prefix)
Tests if this string starts with the specified prefix.
Example:
String str = "Hello World";
boolean result = str.startsWith("Hello"); // true
Explanation: This method checks if the string starts with the prefix "Hello".
startsWith(String prefix, int toffset)
Tests if the substring of this string beginning at the specified index starts with the specified prefix.
Example:
String str = "Hello World";
boolean result = str.startsWith("World", 6); // true
Explanation: This method checks if the substring starting at index 6 starts with "World".
strip()
Returns a string whose value is this string, with all leading and trailing white space removed.
Example:
String str = " Hello World ";
String result = str.strip(); // Hello World
Explanation: This method removes all leading and trailing white space from the string.
stripLeading()
Returns a string whose value is this string, with all leading white space removed.
Example:
String str = " Hello World ";
String result = str.stripLeading(); // Hello World
Explanation: This method removes all leading white space from the string.
stripTrailing()
Returns a string whose value is this string, with all trailing white space removed.
Example:
String str = " Hello World ";
String result = str.stripTrailing(); // Hello World
Explanation: This method removes all trailing white space from the string.
subSequence(int beginIndex, int endIndex)
Returns a character sequence that is a subsequence of this sequence.
Example:
String str = "Hello World";
CharSequence result = str.subSequence(0, 5); // Hello
Explanation: This method returns a subsequence of the string from index 0 to 5.
substring(int beginIndex)
Returns a string that is a substring of this string.
Example:
String str = "Hello World";
String result = str.substring(6); // World
Explanation: This method returns the substring starting from index 6 to the end of the string.
substring(int beginIndex, int endIndex)
Returns a string that is a substring of this string.
Example:
String str = "Hello World";
String result = str.substring(0, 5); // Hello
Explanation: This method returns the substring from index 0 to 5.
toCharArray()
Converts this string to a new character array.
Example:
String str = "Hello";
char[] charArray = str.toCharArray();
Explanation: This method converts the string into a character array.
toLowerCase()
Converts all of the characters in this String
to lower case using the rules of the default locale.
Example:
String str = "HELLO";
String result = str.toLowerCase(); // hello
Explanation: This method converts all characters in the string to lower case using the default locale.
toLowerCase(Locale locale)
Converts all of the characters in this String
to lower case using the rules of the given Locale
.
Example:
String str = "HELLO";
String result = str.toLowerCase(Locale.ROOT); // hello
Explanation: This method converts all characters in the string to lower case using the specified locale.
toUpperCase()
Converts all of the characters in this String
to upper case using the rules of the default locale.
Example:
String str = "hello";
String result = str.toUpperCase(); // HELLO
Explanation: This method converts all characters in the string to upper case using the default locale.
toUpperCase(Locale locale)
Converts all of the characters in this String
to upper case using the rules of the given Locale
.
Example:
String str = "hello";
String result = str.toUpperCase(Locale.ROOT); // HELLO
Explanation: This method converts all characters in the string to upper case using the specified locale.
trim()
Returns a string whose value is this string, with all leading and trailing space removed.
Example:
String str = " Hello World ";
String result = str.trim(); // Hello World
Explanation: This method removes all leading and trailing space characters from the string.
valueOf(char[] data)
Returns the string representation of the char array argument.
Example:
char[] data = {'H', 'e', 'l', 'l', 'o'};
String result = String.valueOf(data); // Hello
Explanation: This method creates a new string that represents the sequence of characters in the array data
.
valueOf(char[] data, int offset, int count)
Returns the string representation of a subarray of the char array argument.
Example:
char[] data = {'H', 'e', 'l', 'l', 'o'};
String result = String.valueOf(data, 1, 3); // ell
Explanation: This method creates a new string that represents a subarray of the char array data
starting at offset
and extending count
characters.
valueOf(boolean b)
Returns the string representation of the boolean argument.
Example:
boolean bool = true;
String result = String.valueOf(bool); // true
Explanation: This method creates a new string that represents the boolean value b
.
valueOf(char c)
Returns the string representation of the char argument.
Example:
char c = 'A';
String result = String.valueOf(c); // A
Explanation: This method creates a new string that represents the character c
.
valueOf(int i)
Returns the string representation of the int argument.
Example:
int i = 123;
String result = String.valueOf(i); // 123
Explanation: This method creates a new string that represents the integer i
.
valueOf(long l)
Returns the string representation of the long argument.
Example:
long l = 123L;
String result = String.valueOf(l); // 123
Explanation: This method creates a new string that represents the long value l
.
valueOf(float f)
Returns the string representation of the float argument.
Example:
float f = 3.14f;
String result = String.valueOf(f); // 3.14
Explanation: This method creates a new string that represents the float value f
.
valueOf(double d)
Returns the string representation of the double argument.
Example:
double d = 3.14159;
String result = String.valueOf(d); // 3.14159
Explanation: This method creates a new string that represents the double value d
.
Conclusion
This comprehensive cheat sheet provides a quick reference to all the Java String
methods, their descriptions, examples, and explanations. Mastering these methods will enable you to handle strings more effectively in your Java programs. Keep this guide handy to improve your efficiency and understanding of string manipulation in Java. Happy coding!
Comments
Post a Comment
Leave Comment