String Methods in Java

1. Overview

In this tutorial, we’ll learn about common methods from the String class and how to use them.

3. String Methods

The String represents a reference data type and consists of a set of characters.

Moreover, every character within the value has its own index. An index is a number that marks the place of each character. They start with 0 and increment by one for every next character.

Furthermore, the String class contains many methods that can come in handy if we want to manipulate String values. However, we should always keep in mind the strings are immutable.

Now, let’s examine the most common String methods.

3.1. length()

Firstly, let’s start with a straightforward one. The length() method returns the total number of characters from a String object.

Method Signature

int length()

String s = “animals”;
System.out.println(s.length()); // 7

Therefore, if we call the length() method on the variable containing the value “animal“, the method will return 7 as a result.

Additionally, counting starts with 1 and increments by one for each character.

3.2. charAt()

Secondly, the charAt() method searches and returns the character on the given index.

Method Signature

char charAt(int index)

String string = "animals";
System.out.println(string.charAt(0));   // a
System.out.println(string.charAt(6));   // s

Furthermore, let’s see what would happen if we pass the index that doesn’t exist:


The code will compile and run. However, the line will cause java.lang.StringIndexOutOfBoundsException and the program will end.

3.3. indexOf()

The indexOf() method is reversed charAt() method. Furthermore, the method accepts the character as an argument and returns the first index that contains the passed value.

Additionally, the method accepts a char or String value as a parameter.

Method Signature

int indexOf(char ch) / int indexOf(String str)

int indexOf(char ch, int fromIndex) / int indexOf(String str, int fromIndex)

String a = "animal";
System.out.println(a.indexOf('a')); // 0
System.out.println(a.indexOf("al")); // 4
System.out.println(a.indexOf("abc")); // -1

Moreover, the method returns -1 if the given value doesn’t exist in a String.

Furthermore, as a second argument, we can pass the index value from where we’d like to start searching.

System.out.println(a.indexOf('a', 4)); // 4
System.out.println(a.indexOf("al", 5)); // -1

Lastly, we can use the lastIndexOf() method to retrieve the last appearance of the given value:

System.out.println(a.lastIndexOf('a')); // 4

3.4. substring()

The substring() method returns a partial String value. We can pass one or two parameters.

The first parameter represents the index we’d like to start from. Therefore, the character on the given index will be the first character of a new value.

The second parameter is optional and it represents an index where we’d like to stop. The character on this index will be excluded from the new value.

Method Signature

int substring(int beginIndex)

int substring(int beginIndex, int endIndex)

However, if we call the method passing only one parameter, a new String value will be created from the given index to the end of a String value.

String s = "animals";
System.out.println(s.substring(3));   // mals
System.out.println(s.substring(3, 4));   // m
System.out.println(s.substring(3, 7));   // mals

Additionally, if we pass the index that doesn’t exist:

System.out.println(s.substring(1, 10));

Execution of the code will cause the java.lang.StringIndexOutOfBoundsException exception.

3.5. toLowerCase() i toUpperCase()

Simply put, the toLowerCase() method converts the value to the lower-cased String and returns the new value. Similarly, the toUpperCase() method converts the value to the upper-cased letters and returns the value.

Method Signature

String toLowerCase(String str)

String toUpperCase(String str)

String s = "animals";
System.out.println(s.toUpperCase()); // ANIMALS
System.out.println("ABc123".toLowerCase()); // ABC123
System.out.println(s); // animals

Since String objects are immutable, the original String value will stay the same.

3.6. equals() i equalsIgnoreCase()

The equals() method checks whether two String objects have the same value.

In the same vein, the equalsIgnoreCase() checks for value equality while ignoring the letter case. Furthermore, the method will convert both objects into lower-cased values and then check for equality.

Method Signature

boolean equals(String str)

boolean equalsIgnoreCase(String str)

System.out.println("abc".equals("ABC")); // false
System.out.println("ABC".equals("ABC")); // true
System.out.println("abc".equalsIgnoreCase("ABC")); // true

3.7. startsWith() i endsWith()

The method startsWith() checks whether the String value starts with the given value. Likewise, the endsWith() method checks if the String value ends with the provided value.

Method Signature

boolean startsWith(String str)

boolean endsWith(String str)

System.out.println("abc".startsWith("a")); // true
System.out.println("abc".startsWith("A")); // false
System.out.println("abc".endsWith("c")); // true
System.out.println("abc".endsWith("a")); // false

3.8. contains()

The contains() method checks whether the String object contains a given value. The value we pass can be on any place inside the String.

Method Signature

boolean contains(String str)

System.out.println("abc".concat("b")); // true
System.out.println("abc".concat("B")); // false

3.9. replace()

The replace() method finds the given character of a String in the value and replaces it with a provided new value.

Method Signature

String replace(char oldChar, char newChar)

String replace(String oldChar, String newChar)

System.out.println("abcabc".replace('a', 'A')); // AbcAbc

3.10. trim()

Finally, let’s check our last method. The trim() method removes whitespaces and tabs from the beginning and the end of a String value.

Method Signature

String trim()

System.out.println(" abc".trim()); // abc
System.out.println("\t   a b c \n".trim()); // a b c

It’s important to note that this method doesn’t remove whitespaces and tabs from the entire value. Just from the beginning and the end.

4. Conclusion

In this tutorial, we learned String methods in Java and how to use them.

As always, the entire examples are available over on GitHub.

Would you like to join us?

We're looking for authors and developers. If you're interested, contact us. 
Looking forward to hearing from you!

Leave a Reply

Your email address will not be published. Required fields are marked *