Strings in Java

Strings in Java

String in Java || String Methods in Java With proper Explanation

The String class in Java provides several methods that allow you to work with strings. Some of the most commonly used methods are:

  • length(): Returns the length of the string (i.e., the number of characters in the string)

  • charAt(int index): Returns the character at the specified index in the 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.

  • indexOf(String str): Returns the index within this string of the first occurrence of the specified substring.

  • toLowerCase(): Converts all of the characters in this string to lower case

  • toUpperCase(): Converts all of the characters in this string to upper case

  • trim(): Returns a new string with leading and trailing white space omitted

  • replace(char oldChar, char newChar): Returns a new string resulting from replacing all occurrences of oldChar with newChar

  • split(String regex): Splits this string around matches of the given regular expression

  • equals(Object anObject): Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

These are just some of the many methods provided by the String class in Java. For a complete list of all the methods available, you can refer to the official Java documentation.

Example :

Part-1 :

// Import the String class from the java.lang package
import java.lang.String;

public class Main {
    public static void main(String[] args) {
        // Create a new String object with the value "Hello, World!"
        // Time complexity: O(1)
        String str = new String("Hello, World!");

        // Print the length of the String
        // Time complexity: O(1)
        System.out.println(str.length());

        // Print the first character of the String
        // Time complexity: O(1)
        System.out.println(str.charAt(0));

        // Print the last character of the String
        // Time complexity: O(1)
        System.out.println(str.charAt(str.length() - 1));

        // Concatenate the String with another String
        // Time complexity: O(1)
        String str2 = str.concat(" This is a test.");
        System.out.println(str2);
    }
}

In this code, we import the String class from the java.lang package, and then create a new String object with the value "Hello, World!". We then use various methods of the String class to manipulate the string, such as length() to get the length of the string, charAt() to get the character at a specific index, and concat() to concatenate two strings together.

The time complexity of the operations performed on the String object are all O(1), since they only involve a constant number of operations. The space complexity is also O(1), since the String object only requires a constant amount of space to store its value.


Part-2:

// Import the String class from the java.lang package
import java.lang.String;

public class Main {
    public static void main(String[] args) {
        // Create a new String object with the value "Hello, World!"
        String str = new String("Hello, World!");

        // Check if the String starts with a given prefix
        // Time complexity: O(m), where m is the length of the prefix
        System.out.println(str.startsWith("Hello")); // true
        System.out.println(str.startsWith("World")); // false

        // Check if the String ends with a given suffix
        // Time complexity: O(m), where m is the length of the suffix
        System.out.println(str.endsWith("World!")); // true
        System.out.println(str.endsWith("Hello"));  // false

        // Check if the String contains a given substring
        // Time complexity: O(n * m), where n is the length of the String and m is the length of the substring
        System.out.println(str.contains("Hello"));  // true
        System.out.println(str.contains("World"));  // true
        System.out.println(str.contains("Foo"));    // false

        // Replace a substring with another string
        // Time complexity: O(n * m), where n is the length of the String and m is the length of the substring
        String str2 = str.replace("World", "Foo");
        System.out.println(str2); // "Hello, Foo!"

        // Convert the String to lowercase
        // Time complexity: O(n), where n is the length of the String
        String str3 = str.toLowerCase();
        System.out.println(str3); // "hello, world!"

        // Convert the String to uppercase
        // Time complexity: O(n), where n is the length of the String
        String str4 = str.toUpperCase();
        System.out.println(str4); // "HELLO, WORLD!"

        // Split the String into an array of substrings, using a given delimiter
        // Time complexity: O(n), where n is the length of the String
        String[] words = str.split(",");
        System.out.println(Arrays.toString(words)); // ["Hello", " World!"]
    }
}

This code demonstrates how to use various methods of the String class to manipulate strings. These methods include startsWith() and endsWith() to check if a string starts or ends with a given prefix or suffix, contains() to check if a string contains a given substring, replace() to replace a substring with another string, toLowerCase() and toUpperCase() to convert the string to lowercase or uppercase, and split() to split the string into an array of substrings using a given delimiter.

The time complexity of these operations depends on the length of the input string and, in some cases, the length of the substring or delimiter. In general, the time complexity ranges from O(1) for operations that only involve


Part-3 :

// Import the String class from the java.lang package
import java.lang.String;

public class Main {
    public static void main(String[] args) {
        // Create a new String object with the value "Hello, World!"
        String str = new String("Hello, World!");

        // Check if the String is empty
        // Time complexity: O(1)
        System.out.println(str.isEmpty()); // false

        // Check if the String is blank (contains only whitespace characters)
        // Time complexity: O(n), where n is the length of the String
        System.out.println(str.trim().isEmpty()); // false

        // Check if the String contains only digits
        // Time complexity: O(n), where n is the length of the String
        System.out.println(str.matches("\\d+")); // false

        // Check if the String contains only letters
        // Time complexity: O(n), where n is the length of the String
        System.out.println(str.matches("[a-zA-Z]+")); // false

        // Check if the String contains only letters and digits
        // Time complexity: O(n), where n is the length of the String
        System.out.println(str.matches("[a-zA-Z\\d]+")); // false

        // Check if the String contains only alphanumeric characters
        // Time complexity: O(n), where n is the length of the String
        System.out.println(str.matches("[\\w]+")); // true

        // Trim the whitespace characters from the beginning and end of the String
        // Time complexity: O(n), where n is the length of the String
        String str2 = str.trim();
        System.out.println(str2); // "Hello, World!"

        // Reverse the String
        // Time complexity: O(n), where n is the length of the String
        StringBuilder sb = new StringBuilder(str);
        String str3 = sb.reverse().toString();
        System.out.println(str3); // "!dlroW ,olleH"
    }
}

This code demonstrates how to use various methods of the String class to check the contents of a string, trim whitespace characters, and reverse the string. These methods include isEmpty() to check if the string is empty, trim() to remove leading and trailing whitespace characters, matches() to check if the string matches a given regular expression, and reverse() to reverse the string.

The time complexity of these operations depends on the length of the input string. In general, the time complexity ranges from O(1) for operations that only involve a constant number of operations, to O(n) for operations that involve iterating over the entire string. The space complexity is also O(n), since the StringBuilder class used to reverse the string requires O(n) space to store the reversed string.

We are goanna learn StringBuilder in Separate Note/Page. [[StringBuilder in Java]]