Home » Java String

Java String

Java String

Strings are a crucial part of any programming language, including the string of Java. We use Strings to represent and manipulate text-based data, which is a large portion of the data we work with daily.

The String class is one of the classes which implement this interface. Hence, the string is an object that represents a sequence of char values.

Strings in Java are unique because, unlike other objects, they are immutable. This means that once a String object is created, it cannot be changed. Instead, each time you manipulate a String, Java creates a new String object.

Different Ways to Create String

There are many ways to create a string object in Java, some of the popular ones are given below.

1. Using string literal

This is the most common way of creating strings. In this case, a string literal is enclosed with double quotes.

String str = "abc"; 
Java

way-to-create-string-java.png

When we create a String using double quotes, JVM looks in the String pool to find if any other String is stored with the same value. If found, it just returns the reference to that String object else it creates a new String object with a given value and stores it in the String pool.

2. Using new keyword

you can create a string using the new keyword by explicitly invoking the constructor of the String

String str = new String("Hello, World!");
Java
String str  =  new String("abc");
char[] a = {'a', 'b', 'c'};
String str2  =  new String(a);
Java

Java String class methods

The java.lang.String class provides many useful methods to perform operations on a sequence of char values.

MethodReturn TypeUse Case
charAt()charThe character at the provided index is returned by charAt().
codePointBefore()intReturns the Unicode of the character before the specified index.
codePointAt()intcodePointAt() returns the Unicode of the character at the specified index.
compareTo()intIt compares two strings lexicographically
compareToIgnoreCase()intIt compares two strings lexicographically, ignoring case differences.
concat()StringA string is appended to the end of another string by this function.
contains()booleanDetermines whether a string contains a given character sequence.
contentEquals()booleanChecks whether a string includes the same character sequence as the provided CharSequence or StringBuffer.
copyValueOf()StringIt returns a String containing all of the characters in the character array.
endsWith()booleanendsWith() determines whether a string contains the provided character at the end.
equals()booleanThis function compares two strings. If the strings are equal, returns true; otherwise, returns false.
equalsIgnoreCase()booleanequalsIgnoreCase() compares two strings without taking case into account.
hashCode()inthashCode() returns the hash code of a string.
indexOf()intIn a string, this function returns the position of the first discovered occurrence of provided characters.
intern()Stringintern() returns the string object’s canonical representation
isEmpty()booleanDetermines whether or not a string is empty.
lastIndexOf()In a string, this function returns the position of the last discovered occurrence of a provided character.
length()intThis function returns the length of the string.
replace()Stringreplace() looks for a specified value in a string and returns a new string with the provided values replaced.
replaceAll()StringEach substring of this string that satisfies the supplied regular expression is replaced with the specified replacement by replaceAll().
split()String[]split() creates an array of substrings from a string
startsWith()booleanstartsWith() determines whether a string begins with the characters supplied.
substring()Stringsubstring() generates a new string that is a substring of the given string.
toLowerCase()StringConverts a string to lowercase letters.
toString()StringReturns the value of a String object.
toUpperCase()StringConverts a string to upper case letters.
trim()StringRemoves whitespace from the beginning and end of a string.
valueOf()StringThe string representation of the provided value is returned.

here’s an example Java code snippet that demonstrates the use of some important methods provided by the String class:

public class StringExample {
    public static void main(String[] args) {
        // Creating a string
        String str = "Hello, World!";
        
        // Length of the string
        int length = str.length();
        System.out.println("Length of the string: " + length);
        
        // Getting character at a specific index
        char ch = str.charAt(7);
        System.out.println("Character at index 7: " + ch);
        
        // Substring
        String substr = str.substring(7, 12);
        System.out.println("Substring from index 7 to 11: " + substr);
        
        // Converting to uppercase
        String upperCase = str.toUpperCase();
        System.out.println("Uppercase string: " + upperCase);
        
        // Converting to lowercase
        String lowerCase = str.toLowerCase();
        System.out.println("Lowercase string: " + lowerCase);
        
        // Index of a substring
        int index = str.indexOf("World");
        System.out.println("Index of 'World': " + index);
        
        // Checking if starts with
        boolean startsWith = str.startsWith("Hello");
        System.out.println("Starts with 'Hello': " + startsWith);
        
        // Checking if ends with
        boolean endsWith = str.endsWith("!");
        System.out.println("Ends with '!': " + endsWith);
        
        // Splitting the string
        String[] parts = str.split(",");
        System.out.println("Splitting the string:");
        for (String part : parts) {
            System.out.println(part.trim());
        }
        
        // Replacing characters
        String replaced = str.replace("World", "Universe");
        System.out.println("After replacing 'World' with 'Universe': " + replaced);
        
        // Trimming whitespace
        String trimmed = "  Hello, World!  ".trim();
        System.out.println("After trimming whitespace: " + trimmed);
    }
}
Java

This code demonstrates:

  • length(): Getting the length of the string.
  • charAt(int index): Accessing characters at specific indices.
  • substring(int beginIndex, int endIndex): Extracting substrings.
  • toUpperCase(), toLowerCase(): Converting the case of the string.
  • indexOf(String str): Finding the index of a substring.
  • startsWith(String prefix), endsWith(String suffix): Checking if the string starts or ends with a specific prefix or suffix.
  • split(String regex): Splitting the string based on a delimiter.
  • replace(CharSequence target, CharSequence replacement): Replacing characters.
  • trim(): Removing leading and trailing whitespace.

String Constant Pool

The string constant pool in Java is a storage area in the heap memory that stores string literals. When a string is created, the JVM checks if the same value exists in the string pool. If it does, the reference to that existing object is returned. Otherwise, a new string object is created and added to the string pool, and its reference is returned.

Here’s an example demonstrating the use of the String constant pool in Java

public class StringConstantPoolExample {
    public static void main(String[] args) {
        // Creating string literals
        String str1 = "hello";
        String str2 = "hello";
        String str3 = new String("hello");
        
        // Checking references
        System.out.println("str1 == str2: " + (str1 == str2)); // true
        System.out.println("str1 == str3: " + (str1 == str3)); // false
        
        // Interning string
        String str4 = str3.intern();
        System.out.println("str1 == str4: " + (str1 == str4)); // true
    }
}
Java

Here’s an example demonstrating the use of the String constant pool in Java:

In this example:

  1. str1 and str2 are both assigned the same string literal "hello". Since string literals are interned, they will refer to the same object in the string constant pool. Therefore, str1 == str2 evaluates to true.
  2. str3 is created using the new keyword, so it will be a separate object from str1 and str2. Therefore, str1 == str3 evaluates to false.
  3. By calling the intern() method on str3, we ensure that it is added to the string constant pool if it’s not already present. The reference returned by intern() is then assigned to str4. Since "hello" is already in the pool, str4 will refer to the same object as str1. Therefore, str1 == str4 evaluates to true.

What Is A Substring In Java?

A substring is a subset of a String. In Java, we can extract a substring from a String using the substring() method. This method comes in two forms:

substring(int beginIndex): This returns a substring from the specified beginIndex till the end of the string.substring(int beginIndex, int endIndex): This returns a substring from beginIndex (inclusive) to endIndex (exclusive).

Here’s an example:

String sentence = "Java is fun";
String subs1 = sentence.substring(5); // Returns "is fun"
String subs2 = sentence.substring(5, 7); // Returns "is"

System.out.println(subs1); // Outputs "is fun"
System.out.println(subs2); // Outputs "is"
Java

Java Strings: Mutable or Immutable

Although it may seem like string values can be changed in previous sections of this article, the actual string value remains unchanged.

The concept of the String Constant Pool is closely tied to string immutability in Java.

In Java, strings are immutable, their values cannot be changed once initialized. This is because a single string object in the String constant pool can have multiple references. Modifying the value of one reference could affect other strings or reference variables, leading to conflicts. To prevent these conflicts, string objects are made immutable in Java.

Let us understand with the help of an example:

// Unmodified string str
String str = "Happy Learning";
System.out.println(str); // Output: Happy Learning

// Modified string str
str = str + " to all";
System.out.println(str); // Output: Happy Learning to all
Java

In Java, strings are immutable. When we concatenate a string like ” to all” with str, a new string value is created. str then points to this newly created value, while the original value remains unchanged. This behavior demonstrates the immutability of strings in Java.

Conclusion

String is a fundamental class used for representing and manipulating textual data in Java programming. Immutable by nature, strings ensure thread safety and memory efficiency. The String constant pool optimizes memory usage by reusing identical string literals, enhancing performance, and reducing memory overhead. String manipulation methods allow for tasks such as concatenation, substring extraction, case conversion, searching, and replacing, facilitating versatile text processing. String comparison involves content comparison with the equals() method and reference comparison with the == operator. Conversion methods enable transformation between strings and other data types while formatting options provide control over string representation. Handling null and empty strings is critical for avoiding errors and ensuring program correctness. Mastery of String operations and nuances is crucial for effective programming, given the ubiquitous use of strings in Java applications for tasks ranging from simple data storage to complex text processing. A solid understanding of String fundamentals empowers developers to create robust and efficient software solutions.

Frequently Asked Questions

Q1. What is a Java String?

Ans: A String is a sequence of characters used to represent textual data. It’s an immutable object, meaning its value cannot be changed after it’s created.


Q2. How do you create a String in Java?

Ans: There are two main ways to create a String by using string literals (e.g., "hello") or by creating an instance of the String class using the new keyword (e.g., new String("hello")).


Q3. What is the String constant pool in Java?

Ans: The String constant pool is a special area in the JVM heap memory where string literals are stored. It helps conserve memory by reusing identical string literals, which improves performance and reduces memory overhead.


Q4. How do you compare Strings in Java?

Ans: You can compare Strings using the equals() method for content comparison. For reference comparison, you can use the == operator, but it’s generally recommended to use equals() for content comparison and == for reference comparison with string literals.


Q5. Can you modify a String in Java?

Ans: No, Strings are immutable, meaning their values cannot be changed after creation. However, you can perform various string manipulation operations.