String class - Notes By ShariqSP

Introduction to String Class

The String class in Java represents a sequence of characters. It is immutable, meaning once a String object is created, its value cannot be changed. String class provides various methods for string manipulation and comparison.

Methods of the String Class:

  1. charAt(int index)
  2. length()
  3. substring(int beginIndex, int endIndex)
  4. equals(Object obj)
  5. indexOf(String str)
  6. toUpperCase()
  7. toLowerCase()
  8. trim()
  9. startsWith(String prefix)
  10. endsWith(String suffix)
  11. replace(char oldChar, char newChar)
  12. replaceAll(String regex, String replacement)
  13. contains(CharSequence s)
  14. isEmpty()
  15. split(String regex)

Examples:

1. charAt(int index):

The charAt() method returns the character at the specified index position in the string.


            String str = "Hello";
            char ch = str.charAt(1);
            System.out.println(ch); // Output: 'e'
                

2. length():

The length() method returns the length of the string.


            String str = "Hello";
            int len = str.length();
            System.out.println(len); // Output: 5
                

3. substring(int beginIndex, int endIndex):

The substring() method returns a substring of the original string, starting from the specified beginIndex (inclusive) and ending at the specified endIndex (exclusive).


            String str = "Hello World";
            String substr = str.substring(6, 11);
            System.out.println(substr); // Output: "World"
                

4. equals(Object obj):

The equals() method compares the content of two strings for equality.


            String str1 = "Hello";
            String str2 = "Hello";
            System.out.println(str1.equals(str2)); // Output: true
                

5. indexOf(String str):

The indexOf() method returns the index of the first occurrence of the specified substring within the string, or -1 if the substring is not found.


            String str = "Hello World";
            int index = str.indexOf("World");
            System.out.println(index); // Output: 6
                

6. toUpperCase():

The toUpperCase() method returns a new string with all the characters converted to uppercase.


            String str = "hello";
            String upperCaseStr = str.toUpperCase();
            System.out.println(upperCaseStr); // Output: "HELLO"
                

7. toLowerCase():

The toLowerCase() method returns a new string with all the characters converted to lowercase.


            String str = "HELLO";
            String lowerCaseStr = str.toLowerCase();
            System.out.println(lowerCaseStr); // Output: "hello"
                

8. trim():

The trim() method removes leading and trailing whitespace from the string.


            String str = "   Hello   ";
            String trimmedStr = str.trim();
            System.out.println(trimmedStr); // Output: "Hello"
                

9. startsWith(String prefix):

The startsWith() method checks if the string starts with the specified prefix.


            String str = "Hello World";
            boolean startsWithHello = str.startsWith("Hello");
            System.out.println(startsWithHello); // Output: true
                

10. endsWith(String suffix):

The endsWith() method checks if the string ends with the specified suffix.


            String str = "Hello World";
            boolean endsWithWorld = str.endsWith("World");
            System.out.println(endsWithWorld); // Output: true
                

11. replace(char oldChar, char newChar):

The replace() method replaces all occurrences of the specified oldChar with the newChar.


            String str = "Hello";
            String replacedStr = str.replace('l', 'x');
            System.out.println(replacedStr); // Output: "Hexxo"
                

12. replaceAll(String regex, String replacement):

The replaceAll() method replaces all substrings that match the given regular expression with the specified replacement string.


            String str = "Hello123";
            String replacedStr = str.replaceAll("\\d", "");
            System.out.println(replacedStr); // Output: "Hello"
                

13. contains(CharSequence s):

The contains() method checks if the string contains the specified sequence of characters.


            String str = "Hello World";
            boolean containsWorld = str.contains("World");
            System.out.println(containsWorld); // Output: true
                

14. isEmpty():

The isEmpty() method returns true if the string is empty (contains no characters), otherwise false.


            String str = "";
            boolean isEmpty = str.isEmpty();
            System.out.println(isEmpty); // Output: true
                

15. split(String regex):

The split() method splits the string into an array of substrings based on the specified regular expression.


            String str = "Hello,World";
            String[] parts = str.split(",");
            for (String part : parts) {
                System.out.println(part);
            }
            // Output:
            // Hello
            // World
                

Interview Questions on String Class

Interview Questions:

  1. What is the String class in Java?
  2. Explain the immutability of strings in Java.
  3. How are strings stored in memory in Java?
  4. What are some important methods provided by the String class?
  5. Explain the difference between the == operator and the equals() method when comparing strings.
  6. What is the significance of the hashCode() method in the String class?
  7. How does the intern() method work in the String class?
  8. Explain the StringBuilder and StringBuffer classes and their differences from the String class.
  9. What is the purpose of the substring() method in the String class?
  10. How does the String class handle internationalization and localization?

Multiple Choice Questions (MCQs):

  1. Which of the following is true about the String class in Java?
    a) String is a primitive data type
    b) String objects are mutable
    c) String objects are stored in the stack memory
    d) String objects are immutable
    Answer: d) String objects are immutable
  2. Which method is used to compare two strings for content equality?
    a) compare()
    b) equals()
    c) compareTo()
    d) isEqual()
    Answer: b) equals()
  3. What is the result of the concatenation operation "Hello" + "World"?
    a) HelloWorld
    b) Hello World
    c) HelloWorld
    d) Hello+World
    Answer: a) HelloWorld
  4. Which method is used to obtain the length of a string?
    a) length()
    b) size()
    c) count()
    d) getSize()
    Answer: a) length()
  5. Which of the following classes is mutable?
    a) String
    b) StringBuilder
    c) StringBuffer
    d) Both StringBuilder and StringBuffer
    Answer: d) Both StringBuilder and StringBuffer