You are currently viewing Java: Everything You Need to Know About the String Class (Part 1)

Java: Everything You Need to Know About the String Class (Part 1)

A string is a sequence of characters in Java. It is a fundamental data type and a class in the Java programming language. Strings are used to represent textual data and are widely used in Java programs for various purposes such as storing and manipulating text-based information.

In Java, strings are immutable, which means that once a string object is created, its value cannot be changed. This immutability property ensures that strings are safe to share and can be used in scenarios where data integrity is crucial.

When it appears that a string is being mutated, what is happening is the creation of a new string and assigning it to a variable. The original string remains unchanged. This behavior might give the impression of mutation, but it aligns with the immutability principle.

Strings in Java are created using string literals, which are sequences of characters enclosed in double quotation marks. For example:

String str = "Hello, Java!";

In the above example, we have declared a string variable named str and assigned it the value “Hello, Java!”, which is a string literal.

Strings in Java have a rich set of methods and operations that allow for various string manipulation tasks, such as concatenation, substring extraction, searching, replacing, and more. The String class provides these methods, making it convenient to work with strings in Java programs.

Exploring String Class Methods

char charAt(int index)

The charAt(int index) method returns the character at the specified index in a string. The index parameter represents the position of the character to retrieve, starting from 0.

Here’s an example program that demonstrates the usage of charAt(int index):

public class Main {

    public static void main(String[] args) {

        String str = "Hello, Java!";

        char char1 = str.charAt(0);
        char char5 = str.charAt(4);
        char charLast = str.charAt(str.length() - 1);

        // Output: 'H'
        System.out.println("Character (1) : " + char1);

        // Output: 'o'
        System.out.println("Character (5) : " + char5);

        // Output: '!'
        System.out.println("Last character: " + charLast);

    }

}

The string str is created with the value “Hello, Java!”. We then use the charAt(int index) method to access specific characters at different indices within the string. Finally, we print the characters retrieved using System.out.println().

The charAt(int index) method is useful when you need to retrieve or manipulate individual characters in a string based on their positions. Remember that the index starts from 0, and accessing an index beyond the length of the string will result in a StringIndexOutOfBoundsException.

IntStream chars()

The chars() method returns an IntStream that represents the characters of a string as integer values. Each integer value in the stream represents the Unicode value of a character in the string.

Here’s an example program that demonstrates the usage of chars():

import java.util.stream.IntStream;

public class Main {

    public static void main(String[] args) {

        String str = "Hello, Java!";

        // Getting the IntStream of characters
        IntStream intStream = str.chars();

        // Printing the characters as integers
        intStream.forEach(System.out::println);

    }

}

In this example, we have a string str with the value “Hello, Java!”. We use the chars() method to obtain an IntStream of the characters in the string. Then, we iterate over the stream using forEach() and print each character as an integer.

As you can see, the chars() method allows us to process the characters in a string as a stream of integers. This can be useful when you need to perform operations or transformations on individual characters of a string.

int codePointAt(int index)

The codePointAt(int index) method returns the Unicode code point value of the character at the specified index in a string. It considers the supplementary characters encoded as surrogate pairs.

Here’s an example program that demonstrates the usage of codePointAt(int index):

public class Main {

    public static void main(String[] args) {

        String str = "Java\uD83E\uDD1D";

        // Retrieve the code point at index 4
        int codePoint = str.codePointAt(4);

        // Print the code point
        System.out.println(codePoint);

        // Convert the code point to its corresponding character
        String character = new String(Character.toChars(codePoint));

        // Output: 🤝
        System.out.println(character);

    }

}

As you can see, the codePointAt(int index) method allows you to retrieve the Unicode code point value of a character at a specific index in a string, even for supplementary characters encoded as surrogate pairs.

int codePointBefore(int index)

The codePointBefore(int index) method returns the Unicode code point value of the character immediately before the specified index in a string. It considers the supplementary characters encoded as surrogate pairs.

Here’s an example program that demonstrates the usage of codePointBefore(int index):

public class Main {

    public static void main(String[] args) {

        String str = "Java\uD83E\uDD1D";

        // Retrieve the code point before index 4
        int codePoint = str.codePointBefore(4);

        // Print the code point
        System.out.println(codePoint);

        // Convert the code point to its corresponding character
        String character = new String(Character.toChars(codePoint));

        // Output: a
        System.out.println(character);

    }

}

In this example, we have a string str with the value “Java\uD83E\uDD1D”, which includes a supplementary character represented by a surrogate pair. We use the codePointBefore(4) method to retrieve the code point value immediately before index 4, which corresponds to the character ‘a’. Then, we convert the code point back to its corresponding character using Character.toChars(codePoint).

As you can see, the codePointBefore(int index) method allows you to retrieve the Unicode code point value of the character immediately before a specified index in a string, considering supplementary characters encoded as surrogate pairs.

int codePointCount(int beginIndex, int endIndex)

The codePointCount(int beginIndex, int endIndex) method returns the number of Unicode code points in the specified range of a string. It counts the code points in the range [beginIndex, endIndex).

Here’s an example program that demonstrates the usage of codePointCount(int beginIndex, int endIndex):

public class Main {

    public static void main(String[] args) {

        String str = "Java\uD83E\uDD1DProgramming";

        // Get the code point count from index 0 to index 8
        int codePointCount = str.codePointCount(0, 8);

        // Output: 7
        System.out.println(codePointCount);

    }

}

In this example, we have a string str with the value “Java\uD83E\uDD1DProgramming”, which contains a supplementary character represented by a surrogate pair. We use the codePointCount(0, 8) method to count the number of Unicode code points in the range from index 0 to index 8. The range includes the characters ‘J’, ‘a’, ‘v’, ‘a’, and the supplementary characters.

As you can see, the codePointCount(int beginIndex, int endIndex) method allows you to determine the number of Unicode code points in a specified range of a string. It is useful when dealing with strings that contain supplementary characters represented by surrogate pairs.

IntStream codePoints()

The codePoints() method returns an IntStream of Unicode code points from a given string. It allows you to iterate over the code points in the string.

Here’s an example program that demonstrates the usage of codePoints():

import java.util.stream.IntStream;

public class Main {

    public static void main(String[] args) {

        String str = "Hello, Java!😊";

        // Get the IntStream of code points
        IntStream codePointsStream = str.codePoints();

        // Print each code point
        codePointsStream.forEach(System.out::println);

    }

}

In this example, we have a string str with the value “Hello, Java!😊”. We use the codePoints() method to obtain an IntStream of code points from the string. Then, we iterate over each code point using the forEach method and print it.

As you can see, the codePoints() method allows you to obtain an IntStream of code points from a string, enabling you to perform operations on each individual code point.

int compareTo(String anotherString)

The compareTo() method compares two strings lexicographically. It returns an integer that indicates the relative order of the strings.

Here’s an example program that demonstrates the usage of compareTo():

public class Main {

    public static void main(String[] args) {

        String str1 = "Dart";
        String str2 = "Java";
        String str3 = "Swift";

        int result1 = str1.compareTo(str2);
        int result2 = str1.compareTo(str3);

        // Output: -6
        System.out.println(result1);

        // Output: -15
        System.out.println(result2);

    }

}

In this example, we have three strings: str1 with the value “Dart”, str2 with the value “Java”, and str3 with the value “Swift”. We use the compareTo() method to compare str1 with str2 and str1 with str3.

The compareTo() method returns an integer value. If the result is negative, it means that the calling string (str1) is lexicographically less than the argument string (str2 or str3). If the result is zero, it means that both strings are lexicographically equal. If the result is positive, it means that the calling string is lexicographically greater than the argument string.

In this case, the result of str1.compareTo(str2) is -6, indicating that “Dart” is lexicographically less than “Java”. The result of str1.compareTo(str3) is -15, indicating that “Java” is lexicographically less than “Swift”.

The compareTo() method is useful when you need to compare strings based on their lexicographical order, such as sorting or searching operations.

int compareToIgnoreCase(String str)

The compareToIgnoreCase() method compares two strings lexicographically, ignoring their case. It returns an integer that indicates the relative order of the strings, regardless of case differences.

Here’s an example program that demonstrates the usage of compareToIgnoreCase():

public class Main {

    public static void main(String[] args) {

        String str1 = "Java";
        String str2 = "JaVA";
        String str3 = "jAva";

        int result1 = str1.compareToIgnoreCase(str2);
        int result2 = str1.compareToIgnoreCase(str3);

        // Output: 0
        System.out.println(result1);

        // Output: 0
        System.out.println(result2);

    }

}

In this example, we have three strings: str1 with the value “Java”, str2 with the value “JaVA”, and str3 with the value “jAva”. We use the compareToIgnoreCase() method to compare str1 with str2 and str1 with str3.

The compareToIgnoreCase() method works similarly to compareTo(), but it ignores the case differences. It returns the same integer values indicating the relative order of the strings, regardless of whether the characters are uppercase or lowercase.

In this case, the result of str1.compareToIgnoreCase(str2) is 0, indicating that “Java” is lexicographically equal to “JaVA” when ignoring case. The result of str1.compareToIgnoreCase(str3) is 0, indicating that “Java” is lexicographically equal to “jAva” when ignoring case.

The compareToIgnoreCase() method is useful when you want to compare strings in a case-insensitive manner.

String concat(String str)

The concat() method appends the specified string str to the end of the invoking string and returns a new string that represents the concatenation of both strings.

Here’s an example program that demonstrates the usage of concat():

public class Main {

    public static void main(String[] args) {

        String str1 = "Hello,";
        String str2 = " Java!";

        String result = str1.concat(str2);

        // Output: Hello, Java!
        System.out.println(result);

    }

}

In this example, we have two strings: str1 with the value “Hello,” and str2 with the value ” Java!”. We use the concat() method to concatenate str1 and str2, and store the result in the result string.

As you can see, the concat() method combines the two strings and produces a new string that represents the concatenation of both. The original strings str1 and str2 are not modified.

The concat() method is a convenient way to join two strings together. It can be useful in various scenarios where string concatenation is required.

boolean contains(CharSequence s)

The contains() method checks whether a specified sequence of characters, represented by the CharSequence parameter s, is present within the invoking string. It returns true if the sequence is found, and false otherwise.

Here’s an example program that demonstrates the usage of contains():

public class Main {

    public static void main(String[] args) {

        String str = "Hello, Java!";

        boolean contains1 = str.contains("Hello");
        boolean contains2 = str.contains("Java");

        // Output: true
        System.out.println(contains1);
        
        // Output: true
        System.out.println(contains2);

    }

}

In this example, we have a string str with the value “Hello, Java!”. We use the contains() method to check whether str contains two different sequences of characters: “Hello” and “Java”. The boolean results are stored in contains1 and contains2 variables, respectively.

As you can see, the contains() method returns true for the sequences “Hello” and “Java” since they are both present in the string str.

The contains() method is handy when you need to determine if a specific substring exists within a string. It allows you to perform substring matching efficiently.

boolean contentEquals(CharSequence cs)

The contentEquals() method checks whether the content of the invoking string is equal to the specified CharSequence parameter cs. It returns true if the content matches exactly, and false otherwise.

Here’s an example program that demonstrates the usage of contentEquals():

public class Main {

    public static void main(String[] args) {

        String str1 = "Hello, Java!";
        String str2 = new String("Hello, Java!");
        StringBuilder stringBuilder = new StringBuilder("Hello, Java!");

        boolean equals1 = str1.contentEquals(str2);
        boolean equals2 = str1.contentEquals(stringBuilder);

        // Output: true
        System.out.println(equals1);

        // Output: true
        System.out.println(equals2);

    }

}

In this example, we have three different objects: str1 is a string literal, str2 is created using the new keyword, and stringBuilder is an instance of StringBuilder containing the same content as str1. We use the contentEquals() method to compare the content of str1 with str2 and stringBuilder.

As you can see, both comparisons using the contentEquals() method return true because the content of str1 is equal to str2 and stringBuilder. The method performs a character-by-character comparison to determine the equality of the content.

The contentEquals() method is useful when you want to check whether the content of a string matches another CharSequence object, such as a String, StringBuilder, or StringBuffer. It allows you to perform content equality checks without explicitly converting the objects to strings.

boolean contentEquals(StringBuffer sb)

The contentEquals() method checks whether the content of the invoking string is equal to the specified StringBuffer parameter sb. It returns true if the content matches exactly, and false otherwise.

Here’s an example program that demonstrates the usage of contentEquals():

public class Main {

    public static void main(String[] args) {

        String str = "Hello, Java!";
        StringBuffer stringBuffer = new StringBuffer("Hello, Java!");

        boolean equals = str.contentEquals(stringBuffer);

        // Output: true
        System.out.println(equals);

    }

}

In this example, we have a string str and a StringBuffer stringBuffer containing the same content. We use the contentEquals() method to compare the content of str with stringBuffer.

As you can see, the comparison using the contentEquals() method returns true because the content of str is equal to stringBuffer. The method performs a character-by-character comparison to determine the equality of the content.

The contentEquals() method is useful when you want to check whether the content of a string matches a StringBuffer object. It allows you to perform content equality checks without explicitly converting the objects to strings.

static String copyValueOf(char[] data)

The copyValueOf() method returns a new String object that represents the character array specified by the data parameter. It creates a string containing the characters of the specified array.

Here’s an example program that demonstrates the usage of copyValueOf():

public class Main {

    public static void main(String[] args) {

        char[] data = {'J', 'a', 'v', 'a'};

        String str = String.copyValueOf(data);

        // Output: Java
        System.out.println(str);

    }

}

In this example, we have a character array data containing the characters ‘J’, ‘a’, ‘v’, and ‘a’. We use the copyValueOf() method to create a new string str that represents the content of the data array.

As you can see, the copyValueOf() method creates a new string str with the same content as the data array.

The copyValueOf() method is useful when you have a character array and you want to create a string representation of its content. It provides a convenient way to convert character arrays to strings without manually iterating over the array elements.

static String copyValueOf(char[] data, int offset, int count)

The copyValueOf() method returns a new String object that represents a subrange of characters from the character array specified by the data parameter. The subrange starts at the offset index and includes count number of characters.

Here’s an example program that demonstrates the usage of copyValueOf():

public class Main {

    public static void main(String[] args) {

        char[] data = {'H', 'e', 'l', 'l', 'o', ',', ' ', 'J', 'a', 'v', 'a', '!'};
        
        // 4 characters starting at index 7
        String str = String.copyValueOf(data, 7, 4);

        // Output: Java
        System.out.println(str);

    }

}

In this example, we have a character array data containing the characters ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘,’, ‘ ‘, ‘J’, ‘a’, ‘v’, ‘a’, and ‘!’. We use the copyValueOf() method with the offset of 7 and count of 4 to create a new string str that represents the subrange of characters from index 7 to 10 (inclusive) of the data array.

As you can see, the copyValueOf() method creates a new string str containing the characters ‘J’, ‘a’, ‘v’, and ‘a’ from the data array.

The copyValueOf() method is useful when you want to extract a specific portion of characters from a character array and create a string representation of that subrange.

Optional<String> describeConstable()

The describeConstable() method is used to describe the constant value of a String instance if it has one. It returns an Optional object that contains the constant value if the String instance is a constant. Otherwise, it returns an empty Optional. It is an optional method introduced in Java 12.

Here’s an example program that demonstrates the usage of describeConstable():

import java.util.Optional;

public class Main {

    public static void main(String[] args) {

        String str = "Java";
        
        Optional<String> descriptor = str.describeConstable();

        // Java
        System.out.println(descriptor.orElse("No descriptor present!"));

    }

}

In this example, we have a string str with the value “Java”. We use the describeConstable() method to obtain a descriptive representation of the string. The method returns an Optional, which may or may not contain a value.

In this case, the describeConstable() method returns a non-empty optional containing the descriptive representation of the string.

Note that the availability and behavior of describeConstable() may vary depending on the implementation of the String class or the specific string value. It is not guaranteed to be available for all strings.

boolean endsWith(String suffix)

The endsWith(String suffix) method is used to check whether a string ends with a specific suffix. It returns true if the string ends with the specified suffix, and false otherwise.

Here’s an example program that demonstrates the usage of endsWith():

public class Main {

    public static void main(String[] args) {

        String str = "Hello, Java";

        boolean endsWithComma = str.endsWith(",");
        boolean endsWithJava = str.endsWith("Java");
        boolean endsWithExclamation = str.endsWith("!");

        // Output: false
        System.out.println(endsWithComma);

        // Output: true
        System.out.println(endsWithJava);

        // Output: false
        System.out.println(endsWithExclamation);

    }

}

In this example, we have a string str with the value “Hello, Java”. We use the endsWith() method to check if the string ends with different suffixes: “,”, “Java”, and “!”. The method returns true if the string ends with the specified suffix and false otherwise.

In this case, the string ends with “Java”, and not with “,” or “!”.

You can use the endsWith() method to perform various string suffix checks in your programs.

boolean equals(Object anObject)

The equals() method is used to compare a string with the specified object. It returns true if the string is equal to the object, and false otherwise.

Here’s an example program that demonstrates the usage of equals():

public class Main {

    public static void main(String[] args) {

        String str1 = "Hello";
        String str2 = "Hello";
        String str3 = "Java";

        boolean isEqual1 = str1.equals(str2);
        boolean isEqual2 = str1.equals(str3);

        // Output: true
        System.out.println(isEqual1);

        // Output: false
        System.out.println(isEqual2);

    }

}

In this example, we have three string variables: str1 with the value “Hello”, str2 with the value “Hello”, and str3 with the value “Java”. We use the equals() method to compare str1 with str2 and str1 with str3. The method returns true if the strings are equal and false otherwise.

In this case, str1 is equal to str2 because they both have the same content, but str1 is not equal to str3 because they have different content. Therefore, the equals() method returns true for the first comparison and false for the second comparison.

boolean equalsIgnoreCase(String anotherString)

The equalsIgnoreCase() method is used to compare a string with another string, ignoring the case of the characters. It returns true if the strings are equal, ignoring case, and false otherwise.

Here’s an example program that demonstrates the usage of equalsIgnoreCase():

public class Main {

    public static void main(String[] args) {

        String str1 = "Hello";
        String str2 = "hello";
        String str3 = "JAVA";

        boolean isEqual1 = str1.equalsIgnoreCase(str2);
        boolean isEqual2 = str1.equalsIgnoreCase(str3);

        // Output: true
        System.out.println(isEqual1);
        
        // Output: false
        System.out.println(isEqual2);

    }

}

In this example, we have three string variables: str1 with the value “Hello”, str2 with the value “hello”, and str3 with the value “JAVA”. We use the equalsIgnoreCase() method to compare str1 with str2 and str1 with str3. The method returns true if the strings are equal, ignoring case, and false otherwise.

In this case, str1 is equal to str2 because they have the same content, ignoring case, but str1 is not equal to str3 because they have different content, even when ignoring case. Therefore, the equalsIgnoreCase() method returns true for the first comparison and false for the second comparison.

static String format(String format, Object… args)

The format(String format, Object… args) method is used to format a string using the specified format string and arguments. It returns a formatted string based on the format string and the provided arguments.

Here’s an example program that demonstrates the usage of format():

public class Main {

    public static void main(String[] args) {

        String name = "Edward Jr.";
        String language = "Java";
        int age = 28;
        double salary = 6000.00;

        String formattedString = String.format("Name: %s, Language: %s, Age: %d, Salary: %.2f", name, language, age, salary);

        // Output: Name: Edward Jr., Language: Java, Age: 28, Salary: 6000.00
        System.out.println(formattedString);

    }

}

In this example, we have a format string “Name: %s, Language: %s, Age: %d, Salary: %.2f”, which contains placeholders %s, %s, %d, and %f for string, string, integer, and floating-point values, respectively. We use String.format() to format the string by replacing the placeholders with the corresponding values of name, language, age, and salary. The formatted string is then stored in the formattedString variable and printed to the console.

As you can see, the format() method allows you to create formatted strings by specifying the format string and providing the necessary arguments.

static String format(Locale l, String format, Object… args)

The format(Locale l, String format, Object… args) method is similar to the format(String format, Object… args) method we discussed earlier. The only difference is that it allows you to specify the locale for localization purposes. It formats the string using the specified locale, format string, and arguments.

Here’s an example program that demonstrates the usage of the format(Locale l, String format, Object… args) method:

import java.util.Locale;

public class Main {

    public static void main(String[] args) {

        String name = "Edward Jr.";
        String language = "Java";
        int age = 28;
        double salary = 6000.00;

        String formattedString = String.format(Locale.US, "Name: %s, Language: %s, Age: %d, Salary: %.2f", name, language, age, salary);
        
        // Output: Name: Edward Jr., Language: Java, Age: 28, Salary: 6000.00
        System.out.println(formattedString);

    }

}

In this example, we specify the locale as Locale.US, which formats the numbers and dates according to the US locale conventions. The rest of the program is similar to the previous format() example, where we provide the format string and arguments to create a formatted string.

String formatted(Object… args)

The formatted(Object… args) method is similar to the format(String format, Object… args) method, but it is an instance method that can be invoked directly on a String object. It formats the string using the provided arguments and returns the formatted string.

Here’s an example program that demonstrates the usage of the formatted(Object… args) method:

public class Main {

    public static void main(String[] args) {

        String name = "Edward Jr.";
        String language = "Java";
        int age = 28;
        double salary = 6000.00;

        String formatString = "Name: %s, Language: %s, Age: %d, Salary: %.2f";
        String formattedString = formatString.formatted(name, language, age, salary);

        // Output: Name: Edward Jr., Language: Java, Age: 28, Salary: 6000.00
        System.out.println(formattedString);

    }

}

In this example, we directly invoke the formatted() method on the format string “Name: %s, Language: %s, Age: %d, Salary: %.2f”, passing the corresponding arguments name, language, age, and salary. The method returns the formatted string, which is then stored in the formattedString variable and printed to the console.

These methods provide flexibility in formatting strings, allowing you to incorporate variables and values into specific patterns.

byte[] getBytes()

The getBytes() method converts the string into a byte array using the platform’s default character encoding. It returns the resulting byte array.

Here’s an example program that demonstrates the usage of the getBytes() method:

public class Main {

    public static void main(String[] args) {

        String str = "Hello, Java!";
        byte[] byteArray = str.getBytes();

        // Output: 72 101 108 108 111 44 32 74 97 118 97 33
        for (byte b: byteArray)
            System.out.printf("%d ", b);

    }

}

In this example, we call the getBytes() method on the string “Hello, Java!” to obtain its corresponding byte array. Then, we iterate over the byte array and print each byte to the console.

byte[] getBytes(String charsetName)

The getBytes(String charsetName) method converts the string into a byte array using the specified character encoding. It takes the name of the character encoding as a parameter and returns the resulting byte array.

Here’s an example program that demonstrates the usage of the getBytes(String charsetName) method:

import java.io.UnsupportedEncodingException;

public class Main {
    
    public static void main(String[] args) {

        String str = "Hello, Java!";

        try {

            byte[] byteArray = str.getBytes("UTF-8");

            // Output: 72 101 108 108 111 44 32 74 97 118 97 33
            for (byte b : byteArray)
                System.out.print(b + " ");

        } catch (UnsupportedEncodingException e) {
            
            // TODO: Handle unsupported encoding exception
            System.out.println(e.getMessage());
            
        }

    }

}

In this example, we call the getBytes() method with the parameter “UTF-8” to convert the string “Hello, Java!” into a byte array using the UTF-8 character encoding. Then, we iterate over the byte array and print each byte to the console.

byte[] getBytes(Charset charset)

The getBytes(Charset charset) method converts the string into a byte array using the specified Charset object. It takes a Charset parameter and returns the resulting byte array.

Here’s an example program that demonstrates the usage of the getBytes(Charset charset) method:

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class Main {

    public static void main(String[] args) {

        String str = "Hello, Java!";

        Charset charset = StandardCharsets.UTF_8;

        byte[] byteArray = str.getBytes(charset);

        // Output: 72 101 108 108 111 44 32 74 97 118 97 33
        for (byte b : byteArray)
            System.out.print(b + " ");

    }

}

In this example, we create a Charset object for the UTF-8 encoding using StandardCharsets.UTF_8. Then, we call the getBytes() method with the charset object as the parameter to convert the string “Hello, Java!” into a byte array using the UTF-8 encoding. Finally, we iterate over the byte array and print each byte to the console.

void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

The getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) method copies a range of characters from the string into the specified character array. It allows you to specify the starting and ending indices of the characters to be copied, along with the destination character array and its starting position.

Here’s an example program that demonstrates the usage of the getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) method:

public class Main {

    public static void main(String[] args) {

        String str = "Hello, Java!";

        char[] charArray = new char[4];

        str.getChars(7, 11, charArray, 0);

        // Output: J a v a
        for (char c : charArray)
            System.out.print(c + " ");

    }

}

In this example, we create a character array of size 4. Then, we call the getChars() method with the parameters (7, 11, charArray, 0) to copy the characters from index 7 to 10 (end index is exclusive) into the character array starting from index 0. Finally, we iterate over the character array and print each character to the console.

int hashCode()

The hashCode() method returns the hash code value of the string. The hash code is generated based on the contents of the string and is used for various purposes, such as indexing data structures like hash tables.

Here’s an example program that demonstrates the usage of the hashCode() method:

public class Main {

    public static void main(String[] args) {

        String str1 = "Hello";
        String str2 = "Java";

        int hashCode1 = str1.hashCode();
        int hashCode2 = str2.hashCode();

        // Output: 69609650
        System.out.println(hashCode1);

        // Output: 2301506
        System.out.println(hashCode2);

    }

}

In this example, we create two strings “Hello” and “Java”. We call the hashCode() method on each string to obtain their respective hash codes. The hash codes are then printed to the console.

Note that the hash code values may vary depending on the platform and JVM implementation.

String indent(int n)

The indent(int n) method returns a string that is indented by the specified number of spaces. It adds the specified number of spaces at the beginning of each line in the original string.

Here’s an example program that demonstrates the usage of the indent(int n) method:

public class Main {

    public static void main(String[] args) {

        String str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.\nAenean blandit facilisis feugiat.";
        
        String indentedString = str.indent(4);
        
        System.out.println(indentedString);
        
    }

}

In this example, we have a string “Lorem ipsum dolor sit amet, consectetur adipiscing elit.\nAenean blandit facilisis feugiat.” containing two lines. We call the indent(4) method on the string to indent it by 4 spaces. The resulting indented string is then printed to the console.

Each line in the original string is indented by 4 spaces.

int indexOf(int ch)

The indexOf(int ch) method returns the index of the first occurrence of the specified character ch in the string. It searches for the character from the beginning of the string and returns the index if found, or -1 if the character is not present.

Here’s an example program that demonstrates the usage of the indexOf(int ch) method:

public class Main {

    public static void main(String[] args) {

        String str = "Hello, Java!";
        int index = str.indexOf('J');

        // Output: 7
        System.out.println(index);

    }

}

In this example, we have a string “Hello, Java!”. We call the indexOf(‘J’) method on the string to find the index of the first occurrence of the character ‘J’. The resulting index is then printed to the console.

The character ‘J’ is found at index 7 in the string.

int indexOf(int ch, int fromIndex)

The indexOf(int ch, int fromIndex) method returns the index of the first occurrence of the specified character ch in the string, starting from the specified index fromIndex. It searches for the character starting from the specified index and returns the index if found, or -1 if the character is not present.

Here’s an example program that demonstrates the usage of the indexOf(int ch, int fromIndex) method:

public class Main {

    public static void main(String[] args) {

        String str = "Hello, Java Programming!";
        int index = str.indexOf('a', 12);

        // Output: 17
        System.out.println(index);

    }

}

In this example, we have a string “Hello, Java Programming!”. We call the indexOf(‘a’, 12) method on the string to find the index of the first occurrence of the character ‘a’, starting from index 12. The resulting index is then printed to the console.

The character ‘a’ is found at index 17 in the string when searching from index 12 onwards.

int indexOf(String str)

The indexOf(String str) method returns the index of the first occurrence of the specified string str in the string. If the string is not found, it returns -1.

Here’s an example program that demonstrates the usage of the indexOf(String str) method:

public class Main {

    public static void main(String[] args) {

        String text = "Hello, Java!";

        int index = text.indexOf("Java");
        
        // Output: 7
        System.out.println(index);

    }

}

In this example, we find the index of the first occurrence of the string “Java” in the string “Hello, Java!” using the indexOf() method. The resulting index is then printed to the console.

If the specified string is not present in the string, the method returns -1.

int indexOf(String str, int fromIndex)

The indexOf(String str, int fromIndex) method returns the index of the first occurrence of the specified string str in the string, starting from the specified fromIndex. If the string is not found, it returns -1.

Here’s an example program that demonstrates the usage of the indexOf(String str, int fromIndex) method:

public class Main {

    public static void main(String[] args) {

        String text = "Hello, Java!";

        int index = text.indexOf("Java", 6);

        // Output: 7
        System.out.println(index);

    }

}

In this example, we find the index of the first occurrence of the string “Java” in the string “Hello, Java!”, starting from index 6 using the indexOf() method. The resulting index is then printed to the console.

If the specified string is not present in the string starting from the specified index, the method returns -1.

String intern()

The intern() method returns a canonical representation of the string. It ensures that the string is unique and refers to the same object in memory, allowing for efficient comparison of strings using reference equality (==).

Here’s an example program that demonstrates the usage of the intern() method:

public class Main {

    public static void main(String[] args) {

        String str1 = new String("Java");
        String str2 = str1.intern();

        // Output: false
        System.out.println(str1 == str2);

        // Output: true
        System.out.println(str1.equals(str2));

    }

}

In this example, we create a new string “Java” using the new keyword, which creates a new object in memory. By calling the intern() method on str1, we obtain a reference to the canonical representation of the string. We compare str1 and str2 using the reference equality operator ==, which returns false because they refer to different objects in memory. However, the equals() method returns true because the contents of the strings are the same.

boolean isBlank()

The isBlank() method checks if a string is empty or contains only whitespace characters. It returns true if the string is blank, and false otherwise.

Here’s an example program that demonstrates the usage of the isBlank() method:

public class Main {

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

        // Output: true
        System.out.println(str1.isBlank());

        // Output: true
        System.out.println(str2.isBlank());

        // Output: false
        System.out.println(str3.isBlank());

    }

}

In this example, we have three strings: str1 is empty, str2 consists of whitespace characters, and str3 contains the non-blank string “Java”. We call the isBlank() method on each string and print the result. The output shows that str1 and str2 are considered blank strings because they are either empty or contain only whitespace characters, while str3 is not blank.

boolean isEmpty()

The isEmpty() method checks if a string is empty, meaning it has a length of 0. It returns true if the string is empty, and false otherwise.

Here’s an example program that demonstrates the usage of the isEmpty() method:

public class Main {

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

        // Output: true
        System.out.println(str1.isEmpty());

        // Output: false
        System.out.println(str2.isEmpty());

    }

}

In this example, we have two strings: str1 is empty, and str2 contains the non-empty string “Java”. We call the isEmpty() method on each string and print the result. The output shows that str1 is empty, while str2 is not.

static String join(CharSequence delimiter, CharSequence… elements)

The join(CharSequence delimiter, CharSequence… elements) method concatenates multiple strings using the specified delimiter. It returns a new string that is the concatenation of the elements, separated by the delimiter.

Here’s an example program that demonstrates the usage of the join() method:

public class Main {

    public static void main(String[] args) {

        String[] languages = {"Dart", "GoLang", "Java", "Kotlin", "Swift"};
        String joinedString = String.join(", ", languages);

        // Output: Dart, GoLang, Java, Kotlin, Swift
        System.out.println(joinedString);

    }

}

In this example, we have an array of languages, and we use the String.join() method to concatenate the elements of the array with a comma and a space as the delimiter. The resulting joined string is then printed to the console.

The join() method effectively joins the elements of the array into a single string with the specified delimiter.

static String join(CharSequence delimiter, Iterable elements)

The join(CharSequence delimiter, Iterable elements) method is similar to the previous join() method but accepts an Iterable collection of elements instead of an array.

Here’s an example program that demonstrates the usage of the join() method with an Iterable collection:

import java.util.Arrays;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        List<String> languages = Arrays.asList("Dart", "GoLang", "Java", "Kotlin", "Swift");

        String joinedString = String.join(", ", languages);
        
        // Output: Dart, GoLang, Java, Kotlin, Swift
        System.out.println(joinedString);

    }

}

In this example, we have a List of languages, and we use the String.join() method to concatenate the elements of the List with a comma and a space as the delimiter. The resulting joined string is then printed to the console.

The join() method works with any Iterable collection, allowing you to join elements from various data structures.

int lastIndexOf(int ch)

The lastIndexOf(int ch) method returns the index of the last occurrence of the specified character within the string. It searches the string backward from the end and returns the index if found, or -1 if the character is not present.

Here’s an example program that demonstrates the usage of the lastIndexOf(int ch) method:

public class Main {

    public static void main(String[] args) {

        String text = "Hello, Java Programming!";
        
        int index = text.lastIndexOf('a');

        // Output: 17
        System.out.println(index);

    }

}

In this example, we find the index of the last occurrence of the character ‘a’ in the string “Hello, Java Programming!” using the lastIndexOf() method. The resulting index is then printed to the console.

The lastIndexOf() method correctly identifies the last occurrence of the character ‘a’ in the string.

int lastIndexOf(int ch, int fromIndex)

The lastIndexOf(int ch, int fromIndex) method is similar to the previous lastIndexOf() method but starts the search from the specified fromIndex position instead of searching the entire string.

Here’s an example program that demonstrates the usage of the lastIndexOf(int ch, int fromIndex) method:

public class Main {

    public static void main(String[] args) {

        String text = "Hello, Java Programming!";

        int index = text.lastIndexOf('a', 14);

        // Output: 10
        System.out.println(index);

    }

}

In this example, we find the index of the last occurrence of the character ‘a’ before the index 14 in the string “Hello, Java Programming!” using the lastIndexOf() method. The resulting index is then printed to the console.

The lastIndexOf() method with the fromIndex parameter correctly searches for the last occurrence of the character ‘a’ before the specified index.

int lastIndexOf(String str)

The lastIndexOf(String str) method returns the index of the last occurrence of the specified string within the string object. It searches the string backward from the end and returns the index if found, or -1 if the string is not present.

Here’s an example program that demonstrates the usage of the lastIndexOf(String str) method:

public class Main {

    public static void main(String[] args) {

        String text = "Hello, Java Programming!";

        int index = text.lastIndexOf("a");

        // Output: 17
        System.out.println(index);

    }

}

In this example, we find the index of the last occurrence of the string “a” in the string “Hello, Java Programming!” using the lastIndexOf() method. The resulting index is then printed to the console.

The lastIndexOf() method correctly identifies the last occurrence of the string “a” in the string.

int lastIndexOf(String str, int fromIndex)

The lastIndexOf(String str, int fromIndex) method is similar to the previous lastIndexOf(String str) method but starts the search from the specified fromIndex position instead of searching the entire string.

Here’s an example program that demonstrates the usage of the lastIndexOf(String str, int fromIndex) method:

public class Main {

    public static void main(String[] args) {

        String text = "Hello, Java Programming!";

        int index = text.lastIndexOf("ram", 19);

        // Output: 16
        System.out.println(index);

    }

}

In this example, we find the index of the last occurrence of the string “ram” before the index 19 in the string “Hello, Java Programming!” using the lastIndexOf() method. The resulting index is then printed to the console.

The lastIndexOf() method with the fromIndex parameter correctly searches for the last occurrence of the string “ram” before the specified index.

int length()

The length() method returns the length of the string, i.e., the number of characters in the string.

Here’s an example program that demonstrates the usage of the length() method:

public class Main {

    public static void main(String[] args) {

        String text = "Hello, Java Programming!";

        int length = text.length();

        // Output: 24
        System.out.println(length);

    }

}

In this example, we get the length of the string “Hello, Java Programming!” using the length() method. The resulting length is then printed to the console.

The length() method correctly returns the length of the string, which in this case is 24.

Conclusion

This concludes Part 1 of our blog series on Java: Everything You Need to Know About the String Class. We covered a range of fundamental methods provided by the Java String class in this first part of our series. We explored methods like lastIndexOf, length, and getBytes, among others, showcasing their usage and significance in string manipulation. Understanding these methods equips you with essential tools for effective string handling in Java.

However, there is still much more to explore. In Part 2 of our blog series, we will continue our exploration of the Java String class, diving into additional methods that offer even more functionality and flexibility. Make sure to join us in Part 2 to deepen your understanding of the Java String class and enhance your string manipulation skills.

I hope you found this information informative. If you would like to receive more content, please consider subscribing to our newsletter!

Leave a Reply