String Class And Methods In Java

A fundamental class that represents a string of characters in Java is called String. As soon as a String object is created, its value cannot be modified since strings in Java are immutable. Any operation that seems to change a String instead generates a new String object with the changed value. Let's learn more about the methods and ways that the String class can be used by looking at some samples.

How to Create a String in Java?

There are various ways to build a String in Java. Here are a few typical ways to build a String:

String Literal:
The most common and simplest way to create a String in Java is by using string literals. A string literal is a sequence of characters enclosed in double quotes.

String str1 = "Hello, World!"; // Using string literal
Using the new Keyword:
You can create a String object using the new keyword, which calls the String constructor.
String str2 = new String("Hello, World!"); // Using new keyword

Here's an illustration of using strings in Java:

public class StringExample {
    public static void main(String[] args) {
        // Creating strings using literals and the new keyword
        String str1 = "Hello, World!";
        String str2 = new String("Java Strings");

        // Length of the string
        int length1 = str1.length();
        int length2 = str2.length();
        System.out.println("Length of str1: " + length1); // Output: 13
        System.out.println("Length of str2: " + length2); // Output: 12

        // Concatenation
        String concatenatedStr = str1.concat(" I'm learning " + str2);
        System.out.println("Concatenated String: " + concatenatedStr);

        // Substring
        String substring = str1.substring(0, 5); // Extracts characters from index 0 to 4 (exclusive)
        System.out.println("Substring: " + substring); // Output: "Hello"

        // Comparison
        boolean areEqual = str1.equals("Hello, World!");
        boolean ignoreCase = str2.equalsIgnoreCase("java strings");
        System.out.println("Are str1 and 'Hello, World!' equal? " + areEqual); // Output: true
        System.out.println("Are str2 and 'java strings' equal (ignore case)? " + ignoreCase); // Output: true

        // Searching
        int index1 = str1.indexOf("W"); // Returns the index of 'W'
        int index2 = str2.lastIndexOf("s"); // Returns the last index of 's'
        System.out.println("Index of 'W' in str1: " + index1); // Output: 7
        System.out.println("Last index of 's' in str2: " + index2); // Output: 10

        // Conversion
        char firstChar = str1.charAt(0); // Get the character at index 0
        char[] charArray = str2.toCharArray(); // Convert the string to a character array
        System.out.println("First character of str1: " + firstChar); // Output: 'H'
        System.out.println("str2 as a character array: " + Arrays.toString(charArray)); // Output: [J, a, v, a,  , S, t, r, i, n, g, s]

        // Case conversion
        String upperCaseStr = str1.toUpperCase();
        String lowerCaseStr = str2.toLowerCase();
        System.out.println("Uppercase str1: " + upperCaseStr); // Output: "HELLO, WORLD!"
        System.out.println("Lowercase str2: " + lowerCaseStr); // Output: "java strings"

        // Trimming
        String stringWithSpaces = "    Spaces at the beginning and end    ";
        String trimmedString = stringWithSpaces.trim();
        System.out.println("Original string: '" + stringWithSpaces + "'");
        System.out.println("Trimmed string: '" + trimmedString + "'");
    }
}
Output
Length of str1: 13
Length of str2: 12
Concatenated String: Hello, World! I'm learning Java Strings
Substring: Hello
Are str1 and 'Hello, World!' equal? true
Are str2 and 'java strings' equal (ignore case)? true
Index of 'W' in str1: 7
Last index of 's' in str2: 10
First character of str1: H
str2 as a character array: [J, a, v, a,  , S, t, r, i, n, g, s]
Uppercase str1: HELLO, WORLD!
Lowercase str2: java strings
Original string: '    Spaces at the beginning and end    '
Trimmed string: 'Spaces at the beginning and end'
In this example, we've shown how to perform several operations on strings, including finding the length, concatenating, extracting substrings, comparing, searching, converting to a char array, changing the case of the characters, and trimming. In Java, strings are frequently employed and are a crucial component of every Java application. 
 
Here are some of the important methods provided by the String class in Java: 

  1. Length:
    int length():
    Returns the number of characters in the String.

  2. Concatenation:
    String concat(String str):
    Concatenates the specified str to the end of the original String and returns a new String.
    String + String: Strings can be concatenated using the + operator.

  3. Substring:
    String substring(int beginIndex):
    Returns a new String that is a substring of the original String, starting from the specified beginIndex. String substring(int beginIndex, int endIndex): Returns a new String that is a substring of the original String, starting from beginIndex and ending at endIndex-1.

  4. Comparison:
    boolean equals(Object anotherObject):
    Checks if the given object (usually another String) is equal to the original String.
    boolean equalsIgnoreCase(String anotherString): Compares two Strings for equality, ignoring the case of characters.
    int compareTo(String anotherString): Compares two Strings lexicographically.
    boolean startsWith(String prefix): Checks if the String starts with the specified prefix.
    boolean endsWith(String suffix): Checks if the String ends with the specified suffix.

  5. Searching:
    int indexOf(int ch):
    Returns the index of the first occurrence of the specified character.
    int indexOf(String str): Returns the index of the first occurrence of the specified String.
    int lastIndexOf(int ch): Returns the index of the last occurrence of the specified character.
    int lastIndexOf(String str): Returns the index of the last occurrence of the specified String.
     
  6. Conversion:
    char charAt(int index): Returns the character at the specified index.
    char[] toCharArray(): Converts the String to a character array.
    byte[] getBytes(): Encodes the String into a sequence of bytes using the platform's default charset.

  7. Case conversion:
    String toLowerCase():
    Converts the String to lowercase.
    String toUpperCase(): Converts the String to uppercase.

  8. Trimming:
    String trim():
    Removes leading and trailing whitespaces from the String.

  9. Formatting:
    static String format(String format, Object... args):
    Returns a formatted String using the specified format String and arguments.

  10. Value Of:
    static String valueOf(dataType data):
    Converts different data types (e.g., int, double, boolean) to their String representation.
Next Post Previous Post