String class

The String class in Java is one of the most widely used and important classes in Java programming. It represents a sequence of characters and is used for storing and manipulating text. The String class is part of the java.lang package, which is automatically imported.

In Java, strings are immutable, meaning once a String object is created, it cannot be modified. Any modification to a string creates a new string object.

1. String Creation

Strings in Java can be created in two primary ways:

  • String Literal:
    When a string is created using double quotes (" "), it is referred to as a string literal. These are stored in a string pool for efficient memory management.

String str1 = "Hello, World!";Code language: JavaScript (javascript)
  • Using the new keyword:
    A new String object can also be created using the new keyword. This forces a new string object to be created, even if the literal string is already present in the pool.
String str2 = new String("Hello, World!");Code language: JavaScript (javascript)

String Pool (Interning)

Java uses a String Pool to store string literals. When you create a string literal, it’s stored in a common pool of strings. If the same string literal already exists in the pool, Java will reuse it instead of creating a new object.

String str1 = "Hello";
String str2 = "Hello";  // Reuses the same object from the string pool

System.out.println(str1 == str2); // Output: true (because they refer to the same object)
Code language: JavaScript (javascript)

However, when a string is created using the new keyword, it doesn’t refer to the string pool by default

String str3 = new String("Hello");
System.out.println(str1 == str3); // Output: false (because str3 is a new object)Code language: JavaScript (javascript)

String Concatenation Using + Operator

We can concatenate strings using the + operator. The + operator is commonly used to join two or more strings together into a single string.

        String firstName = "Mahesh";
        String lastName = "LotusJavaPrince";
        
        // Concatenate strings using + operator
        String fullName = firstName + " " + lastName;
        
        // Print the concatenated string
        System.out.println("Full Name: " + fullName);//MaheshLotusJavaPrince
Code language: JavaScript (javascript)

String class methods

Method Syntax Description
charAt(int index) String charAt(int index) Returns the character at the specified index. Throws StringIndexOutOfBoundsException if out of range.
compareTo(String anotherString) int compareTo(String anotherString) Compares two strings lexicographically. Returns a negative integer, 0, or a positive integer.
compareToIgnoreCase(String anotherString) int compareToIgnoreCase(String anotherString) Compares two strings lexicographically, ignoring case differences.
concat(String str) String concat(String str) Concatenates the specified string to the end of the current string.
contains(CharSequence sequence) boolean contains(CharSequence sequence) Returns true if the string contains the specified sequence of characters.
endsWith(String suffix) boolean endsWith(String suffix) Returns true if the string ends with the specified suffix.
equals(Object anObject) boolean equals(Object anObject) Compares the string with another object for equality, considering case.
equalsIgnoreCase(String anotherString) boolean equalsIgnoreCase(String anotherString) Compares the string with another string, ignoring case.
getBytes() byte[] getBytes() Encodes the string into a byte array using the platform’s default charset.
getBytes(String charsetName) byte[] getBytes(String charsetName) Encodes the string into a byte array using the specified charset.
indexOf(int ch) int indexOf(int ch) Returns the index of the first occurrence of the specified character. Returns -1 if not found.
indexOf(String str) int indexOf(String str) Returns the index of the first occurrence of the specified substring. Returns -1 if not found.
isEmpty() boolean isEmpty() Returns true if the string is empty (i.e., length is 0).
lastIndexOf(int ch) int lastIndexOf(int ch) Returns the index of the last occurrence of the specified character. Returns -1 if not found.
lastIndexOf(String str) int lastIndexOf(String str) Returns the index of the last occurrence of the specified substring. Returns -1 if not found.
length() int length() Returns the length of the string (the number of characters).
replace(char oldChar, char newChar) String replace(char oldChar, char newChar) Replaces all occurrences of the old character with the new character.
replaceAll(String regex, String replacement) String replaceAll(String regex, String replacement) Replaces each substring that matches the given regular expression with the replacement string.
replaceFirst(String regex, String replacement) String replaceFirst(String regex, String replacement) Replaces the first substring that matches the given regular expression with the replacement string.
split(String regex) String[] split(String regex) Splits the string into an array of substrings based on the given regular expression.
startsWith(String prefix) boolean startsWith(String prefix) Returns true if the string starts with the specified prefix.
substring(int beginIndex) String substring(int beginIndex) Returns a substring from the specified starting index to the end of the string.
substring(int beginIndex, int endIndex) String substring(int beginIndex, int endIndex) Returns a substring from the specified starting index to the specified ending index.
toCharArray() char[] toCharArray() Converts the string to a new character array.
toLowerCase() String toLowerCase() Converts all characters of the string to lowercase.
toUpperCase() String toUpperCase() Converts all characters of the string to uppercase.
trim() String trim() Removes leading and trailing whitespace from the string.
valueOf(boolean b) String valueOf(boolean b) Converts the boolean argument to a string representation.
valueOf(char c) String valueOf(char c) Converts the character argument to a string representation.
valueOf(int i) String valueOf(int i) Converts the integer argument to a string representation.
valueOf(long l) String valueOf(long l) Converts the long argument to a string representation.
valueOf(Object obj) String valueOf(Object obj) Converts the object argument to a string representation, calling its toString() method.
toString() String toString() Returns the string itself (since String is an object, this is just a reference to the object).

Program

public class StringDemo {
    public static void main(String[] args) {
        // Initializing String objects with names
        String name1 = "Mahesh";
        String name2 = "LotusJavaPrince";
        String name3 = "Paani";
        
        // 1. length() - Getting the length of the string
        System.out.println("Length of name1: " + name1.length());
        System.out.println("Length of name2: " + name2.length());
        System.out.println("Length of name3: " + name3.length());
        
        // 2. charAt() - Getting the character at a specific index
        System.out.println("Character at index 2 of name1: " + name1.charAt(2));
        
        // 3. substring() - Extracting a substring from the string
        System.out.println("Substring of name2 (index 0 to 5): " + name2.substring(0, 5));
        
        // 4. toLowerCase() - Converting the string to lowercase
        System.out.println("name2 in lowercase: " + name2.toLowerCase());
        
        // 5. toUpperCase() - Converting the string to uppercase
        System.out.println("name3 in uppercase: " + name3.toUpperCase());
        
        // 6. contains() - Checking if the string contains a substring
        System.out.println("Does name2 contain 'Java'? " + name2.contains("Java"));
        
        // 7. replace() - Replacing a substring within the string
        System.out.println("Replace 'Mahesh' with 'Mohan' in name1: " + name1.replace("Mahesh", "Mohan"));
        
        // 8. concat() - Concatenating two strings
        String concatenatedName = name1.concat(" and " + name2);
        System.out.println("Concatenated name: " + concatenatedName);
        
        // 9. startsWith() - Checking if the string starts with a specific prefix
        System.out.println("Does name2 start with 'Lotus'? " + name2.startsWith("Lotus"));
        
        // 10. endsWith() - Checking if the string ends with a specific suffix
        System.out.println("Does name3 end with 'ni'? " + name3.endsWith("ni"));
        
        // 11. indexOf() - Finding the index of a substring in the string
        System.out.println("Index of 'Java' in name2: " + name2.indexOf("Java"));
        
        // 12. trim() - Removing leading and trailing whitespaces
        String nameWithSpaces = "   LotusJavaPrince   ";
        System.out.println("Trimmed name: '" + nameWithSpaces.trim() + "'");
        
        // 13. equals() - Comparing two strings for equality
        System.out.println("Does name1 equal name2? " + name1.equals(name2));
        
        // 14. equalsIgnoreCase() - Comparing two strings ignoring case
        System.out.println("Does 'lotusjavaprince' equal name2 ignoring case? " + "lotusjavaprince".equalsIgnoreCase(name2));
        
        // 15. compareTo() - Comparing two strings lexicographically
        System.out.println("Compare name1 with name2: " + name1.compareTo(name2));
        
        // 16. isEmpty() - Checking if the string is empty
        System.out.println("Is name1 empty? " + name1.isEmpty());
        
        // 17. toCharArray() - Converting string to a character array
        char[] name1Chars = name1.toCharArray();
        System.out.print("Characters of name1: ");
        for (char c : name1Chars) {
            System.out.print(c + " ");
        }
        System.out.println();
        
        // 18. valueOf() - Converting other data types to string
        int num = 100;
        System.out.println("Integer as String: " + String.valueOf(num));
    }
}
/*
Length of name1: 6
Length of name2: 15
Length of name3: 5
Character at index 2 of name1: h
Substring of name2 (index 0 to 5): Lotus
name2 in lowercase: lotusjavaprin
name3 in uppercase: PAANI
Does name2 contain 'Java'? true
Replace 'Mahesh' with 'Mohan' in name1: Mohan
Concatenated name: Mahesh and LotusJavaPrince
Does name2 start with 'Lotus'? true
Does name3 end with 'ni'? true
Index of 'Java' in name2: 5
Trimmed name: 'LotusJavaPrince'
Does name1 equal name2? false
Does 'lotusjavaprince' equal name2 ignoring case? true
Compare name1 with name2: -1
Is name1 empty? false
Characters of name1: M a h e s h 
Integer as String: 100
*/

The String class in Java plays a fundamental role in handling text data and is one of the most widely used classes in the Java API. Strings in Java are immutable, meaning that once a string is created, it cannot be modified. This immutability provides benefits in terms of security, thread-safety, and efficiency, especially when strings are passed across different parts of a program.

Some key takeaways about the String class:

  1. Immutability: Once a string is created, it cannot be altered. Any operation on a string that seems to modify it actually creates a new string object. This ensures that strings are safe to use across threads and reduces the risk of data corruption.

  2. String Pooling: Java optimizes memory usage by maintaining a special pool of strings. When you create a string literal, it’s stored in the string pool. If you create a new string with the same value, the JVM reuses the reference from the pool, reducing memory overhead.

  3. String Methods: The String class comes with a variety of methods to manipulate text. Some common ones include concat(), substring(), toLowerCase(), toUpperCase(), equals(), and split(). These methods allow you to perform operations like case conversion, extraction of parts of the string, and comparison.

  4. Concatenation: The + operator is commonly used for concatenating strings, but for large-scale concatenation (especially in loops), it’s recommended to use StringBuilder or StringBuffer to avoid performance pitfalls.

  5. Performance: Though convenient, string concatenation using the + operator can be inefficient due to the creation of intermediate String objects. For better performance, using StringBuilder or StringBuffer is preferred in such cases.

  6. Usage in Collections: Strings are frequently used as keys in collections like HashMap due to their immutability and the use of efficient hashing techniques.

  7. Unicode Support: Java strings are internally stored as Unicode, meaning they can handle international characters and symbols, making them ideal for global applications.

The String class in Java provides essential functionality for working with text and plays a pivotal role in many Java programs. Its immutability and integration with the Java ecosystem make it a robust choice for handling text, but developers should be mindful of performance issues in scenarios involving repeated string modifications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top