Skip to content

String methods

String methods are special actions you can perform on strings to manipulate, transform, and analyze them in various ways. Whether you're searching for specific characters, converting cases, or splitting strings into pieces, String methods have got you covered!

Now, let's dive into some of the most commonly used String methods with a few friendly examples:

  1. length(): Returns the length of the string.
java
String message = "Hello, world!";
int length = message.length();
System.out.println("Length of the message: " + length); // Output: 13
  1. charAt(int index): Returns the character at the specified index.
java
String word = "Java";
char firstLetter = word.charAt(0);
System.out.println("First letter of the word: " + firstLetter); // Output: J
  1. toUpperCase() and toLowerCase(): Converts the string to uppercase or lowercase.
java
String text = "Hello, World!";
String uppercase = text.toUpperCase();
String lowercase = text.toLowerCase();
System.out.println("Uppercase: " + uppercase); // Output: HELLO, WORLD!
System.out.println("Lowercase: " + lowercase); // Output: hello, world!
  1. substring(int beginIndex, int endIndex): Returns a substring of the original string.
java
String message = "Hello, world!";
String substring = message.substring(7);
System.out.println("Substring: " + substring); // Output: world!
  1. startsWith(String prefix) and endsWith(String suffix): Checks if the string starts or ends with the specified prefix or suffix.
java
String phrase = "Java is fun!";
boolean startsWithJava = phrase.startsWith("Java");
boolean endsWithFun = phrase.endsWith("fun!");
System.out.println("Starts with Java? " + startsWithJava); // Output: true
System.out.println("Ends with fun? " + endsWithFun); // Output: true
  1. indexOf(String str) and lastIndexOf(String str): Returns the index of the first or last occurrence of the specified substring within the string.
java
String sentence = "Java is fun and Java is powerful";
int firstIndex = sentence.indexOf("Java");
int lastIndex = sentence.lastIndexOf("Java");
System.out.println("First occurrence of 'Java' at index: " + firstIndex); // Output: 0
System.out.println("Last occurrence of 'Java' at index: " + lastIndex); // Output: 15
  1. replace(CharSequence target, CharSequence replacement): Replaces all occurrences of a specified substring with another string.
java
String message = "Hello, world!";
String replacedMessage = message.replace("world", "Java");
System.out.println("Replaced message: " + replacedMessage); // Output: Hello, Java!
  1. trim(): Removes leading and trailing whitespace from the string.
java
String paddedText = "   Java is awesome   ";
String trimmedText = paddedText.trim();
System.out.println("Trimmed text: " + trimmedText); // Output: Java is awesome
  1. split(String regex): Splits the string into an array of substrings based on the specified regular expression.
java
String names = "Alice,Bob,Charlie";
String[] nameArray = names.split(",");
for (String name : nameArray) {
    System.out.println(name);
}
// Output:
// Alice
// Bob
// Charlie
  1. isEmpty(): Returns true if the string is empty (i.e., has zero length).
java
String emptyString = "";
String nonEmptyString = "Hello";
System.out.println("Is empty string empty? " + emptyString.isEmpty()); // Output: true
System.out.println("Is non-empty string empty? " + nonEmptyString.isEmpty()); // Output: false
  1. substring(int beginIndex): Returns a substring starting from the specified index to the end of the string.
java
String message = "Hello, world!";
String substring = message.substring(7);
System.out.println("Substring: " + substring); // Output: world!
  1. equalsIgnoreCase(String anotherString): Compares the string to another string, ignoring case considerations.
java
String str1 = "Hello";
String str2 = "hello";
boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2);
System.out.println("Are the strings equal (ignore case)? " + isEqualIgnoreCase); // Output: true
  1. contains(CharSequence s): Checks if the string contains the specified sequence of characters.
java
String sentence = "Java is fun and powerful";
boolean containsWord = sentence.contains("fun");
System.out.println("Does the sentence contain the word 'fun'? " + containsWord); // Output: true
  1. toUpperCase(Locale locale) and toLowerCase(Locale locale): Converts the string to uppercase or lowercase, using the specified locale for case conversion.
java
String text = "Привет, мир!";
Locale russianLocale = new Locale("ru", "RU");
String uppercase = text.toUpperCase(russianLocale);
String lowercase = text.toLowerCase(russianLocale);
System.out.println("Uppercase: " + uppercase); // Output: ПРИВЕТ, МИР!
System.out.println("Lowercase: " + lowercase); // Output: привет, мир!
  1. replaceAll(String regex, String replacement): Replaces all substrings that match the specified regular expression with the given replacement string.
java
String text = "Java is a programming language";
String replacedText = text.replaceAll("Java", "JavaScript");
System.out.println("Replaced text: " + replacedText); // Output: JavaScript is a programming language

Absolutely, let's explore a few more handy String methods:

  1. concat(String str): Concatenates the specified string onto the end of the current string.
java
String firstName = "John";
String lastName = "Doe";
String fullName = firstName.concat(" ").concat(lastName);
System.out.println("Full name: " + fullName); // Output: John Doe
  1. valueOf(primitive data type) methods: Converts primitive data types and objects to strings.
java
int num = 42;
double value = 3.14;
boolean flag = true;

String strNum = String.valueOf(num);
String strValue = String.valueOf(value);
String strFlag = String.valueOf(flag);

System.out.println("String value of num: " + strNum); // Output: 42
System.out.println("String value of value: " + strValue); // Output: 3.14
System.out.println("String value of flag: " + strFlag); // Output: true
  1. trim(): Removes leading and trailing whitespace from the string.
java
String paddedText = "   Java is awesome   ";
String trimmedText = paddedText.trim();
System.out.println("Trimmed text: " + trimmedText); // Output: Java is awesome
MethodDescription
length()Returns the length of this string.
isEmpty()Returns true if, and only if, length() is 0.
charAt(int index)Returns the character at the specified index.
codePointAt(int index)Returns the Unicode code point value at the specified index.
codePointBefore(int index)Returns the Unicode code point value before the given index.
codePointCount(int beginIndex, int endIndex)Returns the number of Unicode code points in the specified text range of this String.
offsetByCodePoints(int index, int codePointOffset)Returns the index within this String that is offset from the given index by codePointOffset.
getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)Copies characters from this string into the destination character array.
getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin)Encodes characters from this string into a sequence of bytes using the platform's default charset, storing the result into the given byte array.
getBytes(String charsetName)Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
getBytes(Charset charset)Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.
getBytes()Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
equals(Object anObject)Compares this string to the specified object.
equalsIgnoreCase(String anotherString)Compares this string to another string, ignoring case considerations.
compareTo(String anotherString)Compares two strings lexicographically.
compareToIgnoreCase(String str)Compares two strings lexicographically, ignoring case differences.
regionMatches(int toffset, String other, int ooffset, int len)Tests if the specified region of this string matches the specified region of another string.
regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)Tests if the specified region of this string matches the specified region of another string, ignoring case if specified.
startsWith(String prefix, int toffset)Tests if this string starts with the specified prefix beginning a specified index.
startsWith(String prefix)Tests if this string starts with the specified prefix.
endsWith(String suffix)Tests if this string ends with the specified suffix.
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.
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.
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.
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.
substring(int beginIndex)Returns a new string that is a substring of this 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.
subSequence(int beginIndex, int endIndex)Returns a new character sequence that is a subsequence of this sequence.
concat(String str)Concatenates the specified string to the end of this string.
replace(char oldChar, char newChar)Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
matches(String regex)Tells whether or not this string matches the given regular expression.
contains(CharSequence s)Returns true if and only if this string contains the specified sequence of char values.
replaceFirst(String regex, String replacement)Replaces the first substring of this string that matches the given regular expression with the given replacement.
replaceAll(String regex, String replacement)Replaces each substring of this string that matches the given regular expression with the given replacement.
replace(CharSequence target, CharSequence replacement)Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
split(String regex, int limit)Splits this string around matches of the given regular expression.
split(String regex)Splits this string around matches of the given regular expression.
toLowerCase(Locale locale)Converts all of the characters in this String to lower case using the rules of the given Locale.
toLowerCase()Converts all of the characters in this String to lower 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.
toUpperCase()Converts all of the characters in this String to upper case using the rules of the default locale.
trim()Returns a copy of the string, with leading and trailing whitespace omitted.
toCharArray()Converts this string to a new character array.
intern()Returns a canonical representation for the string object.
valueOf(Object obj)Returns the string representation of the Object 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(boolean b)Returns the string representation of the boolean argument.
valueOf(char c)Returns the string representation of the char argument.
valueOf(int i)Returns the string representation of the int argument.
valueOf(long l)Returns the string representation of the long argument.
valueOf(float f)Returns the string representation of the float argument.
valueOf(double d)Returns the string representation of the double argument.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.