Strings in Java and Immutability

Photo by Alexandra on Unsplash

Strings in Java and Immutability

Hey there! This article is going to be your ultimate guide to working with Strings in Java. You'll learn everything you need to know, from the basics of creating and manipulating Strings to more advanced topics like regular expressions and String immutability. You can use the handy table of contents below to easily navigate through the article. Let's get started!

Bonus: There are a few practice questions at the end of the writing that will help you prepare for your next interview and evaluate your knowledge.

TL;DR: This article is a guide to working with Strings in Java. It covers creating, manipulating, and performing operations on Strings, as well as best practices and tips for working with them.

Table of Contents

  1. Introduction to Strings in Java

  2. How to create Strings

  3. Interview/Practice Questions

  4. Conclusion

Introduction to Strings in Java

In Java, a string is a sequence of characters. It is a class in Java that comes under the java.lang package. Strings are immutable which means that once a string object is created, it cannot be modified. In a simpler term, it means that when you create a String variable let’s say “fullname” and the value is John then you realized that you didn't include the lastname Deo and you need to modify or correct it to “John Deo” the moment you do that using any string method it will create a new String object.

Here is an example to illustrate this concept:

String fullname = "John";
String correctname = str1.concat(" Deo");
System.out.println(fullname); // Output: "John"
System.out.println(correctname); // Output: "John Deo"

In this example, fullname is the original string "John". When we call the concat() method on fullname, it appears as though we are modifying fullname by adding " Deo" to the end of it. However, what is actually happening is that a new string object is being created ("John Deo") and assigned to correctname. The original string object, fullname, remains unchanged.

Why are String Immutable.

In Java, strings are immutable for several reasons, including

  1. security concerns as string objects are often used to store sensitive information such as passwords, security tokens, or encryption keys and if strings were mutable, it would be possible for an attacker to modify the contents of a string object, potentially compromising the security of the system,

  2. thread safety concerns as in a multithreaded environment, mutable strings can lead to race conditions and synchronization issues, and by making strings immutable, Java ensures that they can be safely shared across multiple threads without the need for synchronization,

  3. performance concerns as immutable objects are more efficient than mutable ones because they can be safely shared across multiple threads without the need for locking, and this can lead to better performance in multithreaded environments,

  4. caching concerns as Java can cache immutable strings, which can improve performance by reducing the number of objects that need to be created.

How to create Strings

To create a string in java you can use different methods which includes using string literal, using String constructor, and creating a string from another string.

  • Example:
//Using  literal
String myStringOne = "Java is a programming language";

//Using Constructor
char[] helloArray = {'H', 'e', 'l', 'l', 'o', ','};
String helloString = new String(helloArray);

String fullname = "John Deo";
String subString = fullname.substring(0, 4); // "John"
String replacedName = fullname.replace("Deo", "Mark")//John Mark

String Vs StringBuilder Vs StringBuffer

It is often better to use a StringBuilder or StringBuffer object for string manipulation, which allows for more efficient modification of strings.

Here is an example of using a StringBuilder to concatenate two strings:

StringBuilder sb = new StringBuilder("hello");
sb.append(" world");
String result = sb.toString();
System.out.println(result); // Output: "hello world"

In this example, we create a StringBuilder object, sb, and use its append() method to add " world" to the end of the original string "hello". Because StringBuilder is mutable, we can modify the contents of sb without creating a new object. Finally, we convert sb to a string using the toString() method and assign the result to result.

Interview Question

  1. Can you explain the difference between String, StringBuilder, and StringBuffer in terms of thread safety? Write a code example to demonstrate.

  2. How can you reverse a String in Java without using the reverse() method of StringBuilder or StringBuffer? Write a code example to demonstrate.

  3. Can you explain what the String pool is in Java? Write a code example to demonstrate how Strings are stored in the pool.

  4. How can you compare two Strings lexicographically in Java? Write a code example to demonstrate.

  5. Can you explain how the String concatenation operator (+) works in Java? Write a code example to demonstrate.

  6. How can you extract a substring from a String using regular expressions in Java? Write a code example to demonstrate.

  7. How can you convert a String to a byte array in Java? Write a code example to demonstrate.

  8. Can you explain the difference between String.format() and System.out.printf() methods in Java for formatting Strings? Write a code example to demonstrate.

  9. How can you convert a String to a Date object in Java? Write a code example to demonstrate.

  10. Can you explain how the intern() method of String works in Java? Write a code example to demonstrate.

Conclusion and Additional Resources

we cover everything related to working with Strings in Java, from basic concepts such as creating and String immutability. We explain the concept of immutability, why Strings are immutable, and provide instructions on how to create Strings in Java. Lastly, our guide delves into the differences between String, StringBuilder, and StringBuffer and includes examples on how to use each one.

Did you find this article valuable?

Support Sylvester Amaechi by becoming a sponsor. Any amount is appreciated!