Java Strings - String Pool

Java Strings - String Pool

What is a Java String?

In Java, a string is a sequence of characters. Strings are used to represent text in Java applications. Java provides a built-in String class that makes it easy to create and manipulate strings. Strings in Java are immutable, which means that once a string object is created, its value cannot be changed.?

Creating a Java String:

In Java, you can create a string in several ways:?

Using string literals:?

String str1 = "Hello, World!";?


Using the String constructor:?

String str2 = new String("Hello, World!");?


Using the StringBuilder class:?

StringBuilder sb = new StringBuilder();?

sb.append("Hello, ");?

sb.append("World!");?

String str3 =?sb.toString();??        

String Operations:

Java provides many methods to manipulate strings. Here are some common string operations:?

Concatenation:

String str1 = "Hello";?

String str2 = "World";?

String str3 = str1 + " " + str2; // "Hello World"?


Length:?

String str = "Hello, World!";?

int length =?str.length(); // 13?


Substring:?

String str = "Hello, World!";?

String?substr?=?str.substring(7); // "World!"?


Searching:?

String str = "Hello, World!";?

int index =?str.indexOf("World"); // 7??        

String Formatting:

Java provides several ways to format strings. Here are some examples:?

Using the %s format specifier:

String name = "John";?

String greeting =?String.format("Hello, %s!", name); // "Hello, John!"?


Using the?printf?method:?

String name = "John";?

System.out.printf("Hello, %s!", name); // "Hello, John!"?


Using the StringBuilder class:?

String name = "John";?

StringBuilder sb = new StringBuilder();?

sb.append("Hello, ");?

sb.append(name);?

sb.append("!");?

String greeting =?sb.toString(); // "Hello, John!"??        

String Equality:

In Java, you should always use the equals method to compare strings for equality, rather than the == operator. Here's an example:?

String str1 = "Hello";?

String str2 = new String("Hello");?

boolean?equal = str1.equals(str2); // true?

In this example, str1 and str2 have the same value, but they are not the same object in memory, so == would return false.?

What is the Java String Pool??

The Java string pool is a mechanism that is used to optimize memory usage in Java. When a string object is created in Java, it is stored in the string pool if a string with the same value already exists in the pool. If a string with the same value does not exist in the pool, a new string object is created and stored in the pool.?

String pool is a storage space in the Java heap memory where string literals are stored. It is also known as String Constant Pool or String Intern Pool. It is privately maintained by the Java String class. By default, the String pool is empty. A pool of strings decreases the number of String objects created in the JVM, thereby reducing memory load and improving performance.?

How Does the Java String Pool Work??

When a string is created using a string literal, such as "Hello, World!", the Java runtime checks to see if an instance of the string with the same value already exists in the string pool. If a matching string is found, a reference to that string is returned. If a matching string is not found, a new string object is created and added to the pool.?

Here's an example:?

String str1 = "Hello, World!";?

String str2 = "Hello, World!";?

System.out.println(str1 == str2); // true?

In this example, str1 and str2 both reference the same object in the string pool because they have the same value.?

Please find below hand written notes which can further simplify the concepts and enhance the understanding:

No alt text provided for this image
No alt text provided for this image
No alt text provided for this image
No alt text provided for this image
No alt text provided for this image


String Pool and String Objects:?

It is important to note that not all string objects are going to create new reference in string pool. However, when you create a String object using the new keyword, Java always creates a new object in the heap memory, regardless of whether an identical String exists in the pool (if not exisits then will create one there as well). For example:?

String str1 = new String("Hello, World!");?// Will create one object in heap and will store literal in string pool as well

String str2 = new String("Hello, World!");?// This time it'll create only new object in heap

System.out.println(str1 == str2); // false?

In this example, str1 and str2 are both created using the new keyword, str1 and str2 are indeed distinct objects in the heap memory (with different memory address), even though their contents are the same. Therefore, str1 == str2 returns false (== compares object references).

String Pool and Memory Management:

While the string pool can help reduce memory usage in a Java program, it is important to be aware of how the string pool works to avoid potential memory issues. Because string literals are stored in the string pool, they cannot be garbage collected until the program exits. This can lead to memory leaks if too many string literals are used.?

To avoid memory leaks, you can use the intern method to add a string object to the string pool. Here's an example:?

String str1 = new String("Hello, World!").intern();?

String str2 = new String("Hello, World!").intern();?

System.out.println(str1 == str2); // true?

In this example, str1 and str2 are both added to the string pool using the intern method, so they both reference the same object in the pool. This allows for efficient memory usage without the risk of memory leaks.?

How strings are immutable?

In Java, a string is immutable, which means once a string object is created, its value cannot be changed. In other words, any attempt to modify a string object in any way results in the creation of a new string object. This is a fundamental characteristic of Java's string objects, and it has several benefits.?

Here are some of the reasons why Java strings are immutable:?

1.?Thread Safety: Since string objects are immutable, they are thread-safe, which means they can be shared among multiple threads without the risk of thread interference or memory consistency errors.?

2.?Security: Because string objects cannot be changed, they are also more secure. For example, if you pass a string containing sensitive data, such as a password or a credit card number, as an argument to a method, you can be confident that the method cannot modify the string's value.?

3.?Caching: Because strings are immutable, they can be cached and reused, which can improve performance. For example, when you use the same string literal multiple times in your code, the JVM can reuse the same string object rather than creating multiple copies of the same value.?

Papitha Sekaran

Senior Technical Lead | Full Stack Developer | Driving Collaborative Development for Enhanced User Experiences

7 个月

I appreciate you sharing the notes. I would like to comment on the following. Please correct me if I am wrong. Under String Pool and String Objects section, String objects that are created using the new keyword are not stored in the string pool is an incorrect statement. Sring str1 = new String("Hello, World!");? String str2 = new String("Hello, World!");? The above two statement creates their respective string objects in heap memory and checks whether the string literal "Hello, World!" is present in the string pool or not. If the string literal “Hello, World!” is not present in the string pool then it will place this string literal in the string pool else it will skip it.? So, the first statement in this example will add the string literal "Hello, World!" to SCP, while the second statement won't add it as it is already available in SCP (added by statement 1). str1==str2 is false because str1 and str2 are two different objects and?have different memory address (== compares object references, it checks to see if the two operands point to the same object (not equivalent objects))

Mohammad Machhaliya

Backend Developer || Four Star on CodeChef || Specialist CodeForces || Global rank 139 in CodeChef starter 54

8 个月

Muhammad Noman Thank you for sharing it. it cleared all my doubts specially that hand written notes. I gave 1-2 hours to understand it properly, then found this masterpiece. Thank you again.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了