Immutable Strings in Java Programming

JavaJavaBeginner
Practice Now

Introduction

This lab will guide you through the benefits of using immutable Strings in Java programming. You will learn why Strings in Java are immutable and how they can increase the overall performance of your application. By the end of this lab, you will grasp the importance of using immutable Strings and know how to create and use them in your program.

Create a Java file

First, create a Java file named ImmutableString.java in the ~/project directory. This file will contain the code for this lab. Use the following command to create the file.

touch ImmutableString.java

Create a String Variable

In this step, create a String variable to store your name. Use the following code to create a String.

String name = "MyName";

Note: The String class is immutable in Java programming.

Create the String Pool

The String pool is a memory location inside the heap memory that stores all the strings and optimizes memory used by the Strings. In this step, create a few Strings in the String pool by assigning the same value to multiple variables. Use the following code.

String str1 = "String";
String str2 = "String";

Create a Separate String

In some situations, we may want to dedicate a separate space to a String. In this step, create a separate String using the new keyword. Use the following code.

String str3 = new String("String");

Note: Creating a separate String takes up more memory than using the String pool.

Make Strings Secure

Strings are often used to store sensitive information such as usernames, passwords, and URLs. Make the strings secure by making them immutable. In this step, use an immutable String to store a password. Use the following code.

final String password = "SecurePassword";

Note: The final keyword makes the String immutable. No one can alter the value of the String after it has been assigned.

Make Strings Thread-Safe

In Java, immutable objects are thread-safe. Multiple threads can simultaneously access the String. In this step, create a method that accesses an immutable String from multiple threads.

class ThreadSafe implements Runnable {
  public void run() {
    System.out.println("Thread Safe Immutable String: " + password);
  }
}

Note: The above code creates a new thread-safe object and sets the password string as its value. The run method of the object simply prints the value of the string.

Hashcode Caching

The immutability of Strings makes them perfect for use in collections. In particular, collections that use hashing to store objects. In this step, use an immutable String as a key in a HashMap. Use the following code.

HashMap<String, Integer> map = new HashMap<String, Integer>();

map.put(str1, 1);
map.put(str2, 2);

Note: Since the String class is immutable, the Hashcode of the String remains the same. Using mutable objects as keys in a HashMap can cause inconsistencies as the value can change after being inserted.

Compile and Run Java File

In this step, navigate to the ~/project directory and compile the ImmutableString.java file using the following command.

javac ImmutableString.java

Note: The javac command compiles the Java file and generates a .class file.

Use the following command to run the Java program.

java ImmutableString

The output of the program should be:

Thread Safe Immutable String: SecurePassword

Modify Variable Reference

Immutable Strings cannot be modified. In this step, try to modify the value of an immutable String by updating the reference of the object. Use the following code to update the String reference.

name = "NewName";

This code will throw an error, because Strings in Java are immutable.

Summary

Immutable Strings provide many benefits in Java programming. They are thread-safe, secure, and optimize memory usage. By using immutable Strings in your Java program, you can reduce the possibility of errors and create a more efficient and secure application.

Other Java Tutorials you may like