Java String Essentials: A Beginner’s Guide

ChiragChirag
5 min read

In this post, we’re going to explore one of the most essential and intriguing data types in Java: Strings. For many newcomers, especially those coming from languages like C, C++, navigating Strings in Java can be a bit tricky at the beginning. Unlike C, C++, where you can easily create, manipulate, and change strings, Java approaches Strings in a different way, which can catch beginners off guard.

Getting a good grasp of Strings is really important, especially since they often come up in technical interviews for new graduates looking for Java positions. But don’t stress — by the time you finish this blog, you’ll have a solid understanding of how Strings operate in Java.

First, let’s start with the most intuitive and easy approach to using Strings in Java. We can use the String class to create a reference, assign it a value, and then print it.

String name = "yourgoodname";
System.out.println(name);
//Output -> yourgoodname

In this example, we created a String reference called name and assigned it a value directly using double quotes ("yourgoodname"). When you print the name, Java automatically interprets the value and displays it on the console.

Now lets take deep dive and understand things more clearly but before that we will use another syntax to do this exact same thing.

String name = new String("yourgoodname");
System.out.println(name);

//Output -> yourgoodname

Accessibility

In languages like C and C++, you can directly access individual characters in a string using syntax like string_name[index]. For example, in C++:

string name = "iamastring";
cout<<name[0];

//Output -> i

However, Java doesn’t work this way because Strings are immutable. To access a specific character, you must use the charAt(index) method provided by the String class.

Why are Strings Immutable? How Do You Modify Them?

The reason Strings are immutable in Java has to do with something called the String Pool. Let’s take a closer look at how this works, as it will help you understand why immutability is useful and how you can handle situations when you need to change strings.

The String Constant Pool

The String Pool (or String constant pool) is a special memory area in Java’s heap. When you create a string using double quotes (e.g., String s = "hello";), the JVM checks the String Pool to see if the same literal already exists. If it does, the reference to the existing string is returned instead of creating a new object.

String s1 = "hello";
String s2 = "hello";
System.out.println(s1 == s2);  // true

In this case, both s1 and s2 point to the same object in the pool. This saves memory because Java avoids creating duplicate string objects.

Immutability ensures that the contents of strings cannot be changed, which is what makes this memory optimization possible. If one reference could modify the string, all other references pointing to the same object would be affected.

s1.equals(s2) V/S ==

  • s1.equals(s2): This method checks if two strings have the same content, regardless of whether they are the same object in memory.

  • ==: This operator checks if two references point to the exact same object in memory. It does not compare the actual content of the strings.

// WORKING WITH .equals()

String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1.equals(s2));  // true, contents are the same
//Working with ==

String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2);  // false, they are different objects

Here, even though s1 and s2 contain the same text, == returns false because they are two distinct objects in memory, as new String() always creates a new object on the heap, bypassing the String Pool.

Why new String("hello") != new String("hello")?

When you use new String("hello"), it forces the creation of a new String object on the heap, even if the same string exists in the String Pool.

What About Performance and Mutability?

At this point, you might be wondering: if Strings are immutable and every modification creates a new String object, wouldn't that cause performance issues, especially when working with a large number of string manipulations? The answer is yes. Repeatedly creating new String objects can lead to unnecessary overhead, as new objects need to be allocated and garbage collected each time a change is made.

To solve this problem, Java provides two mutable alternatives to String: StringBuilder and StringBuffer. These classes allow you to modify strings without creating new objects for every modification, providing a more efficient solution for string manipulations.

StringBuilder and StringBuffer

  • StringBuilder: This class allows you to modify strings without creating new objects each time. It is faster but not thread-safe, making it ideal for single-threaded scenarios.
StringBuilder sb = new StringBuilder("hello");
sb.append(" world");
System.out.println(sb.toString());  // Output -> "hello world"
  • StringBuffer: Similar to StringBuilder, but it is thread-safe. If you need to modify strings in a multi-threaded environment, use StringBuffer.
StringBuffer sb = new StringBuffer("hello");
sb.append(" world");
System.out.println(sb.toString());  // Output -> "hello world"

For more information on the various methods available in the String class, such as charAt(), substring(), and equals(), you can refer to the official Java documentation for Strings.

In conclusion, Java’s String class is designed to be immutable for security, memory efficiency, and thread safety, and the String Pool plays a crucial role in optimizing memory usage. For mutable strings, StringBuilder and StringBuffer provide the flexibility needed for more dynamic modifications.

Bonus for reading till here →

Q. What is Thread Safe?

Thread-safe refers to code or objects that can be accessed and modified by multiple threads simultaneously without leading to data corruption or unexpected behavior. It ensures that only one thread can modify the object at a time, typically using synchronization techniques to maintain data integrity.

0
Subscribe to my newsletter

Read articles from Chirag directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Chirag
Chirag