Lab Java String methods

Objective

In this lab, you will explore and demonstrate the built-in methods in the String class. These methods help you manipulate the String data type. By the end of this lab learners will be able to describe the Strings methods and use Java Strings Methods.

Instructions

length() method

The length() method returns the length of the string, or it returns the count of the total number of characters present in the string.

Example:

Public class lenthDemo {
    public static void main(String[] args) {
        String str1 = "Java";
        String str2 = "";

        System.out.println(str1.length());  // 4
        System.out.println(str2.length());  // 0
        System.out.println("Java".length());  // 4
        System.out.println("Java\\\\n".length()); // 5
        System.out.println("Learn Java".length()); // 10
    }
}

Output:

isEmpty() method:

This method checks whether the String contains anything or not. If the Java String is empty, it returns true or false.

Example:

Output:

trim() method:

The Java string trim() method removes the leading and trailing spaces. It checks the Unicode value of the space character (‘\u0020’) before and after the string. If it exists, then remove the spaces and return the omitted string.

Example:

toLowerCase() method:

The toLowerCase() method converts all the characters of the String to lowercase.

Example:

Output:

toUpperCase() method:

The toUpperCase() method converts all of the String characters to uppercase.

Example:

Output:

concat() method:

The Java String class provides the concat() method. This method combines a specific string at the end of another string, and ultimately returns a combined string.

Example:

split() method:

The split() method divides the string at the specified regex and returns an array of substrings.

Example:

Output:

charAt() method:

The charAt() method gets the character at the specified index.

Example:

compareTo() method:

The compareTo() method compares the given string with the current string.

Example:

substring() method:

The substring() method extracts a substring from the string and returns it.

Example:

indexOf() method:

The indexOf() method returns the index of the first occurrence of the specified character/substring within the string.

Example:

contains() method:

The contains() method checks whether the specified string (sequence of characters) is present in the string or not.

Example:

replace() method:

The replace() method replaces each matching occurrence of the old character/text in the string with the new character/text.

Example:

Java String compares

There are three ways to compare String in Java:

By Using equals() Method

The String class's equals() method compares the original content of the string.

Example:

By Using == Operator

The == operator compares references, not values.

Example:

By compareTo() Method

The compareTo() method compares values lexicographically.

Example:

Last updated