×

What is string in Java why it's immutable

String in Java

Strings are a series of characters commonly used in Java language, which are considered objects in the Java. To create and manipulate strings, java will provide the String class. Any application program must contain a String as a kind of variable. To store different attributes like usernames and passwords, etc., string references are employed. String objects are immutable in Java. Immutable simply indicates that something cannot be altered or changed.

Creation of String?

We have two different ways to create String

  1. String Literal method
  2. New Keyword method

String Literal is simply created by using double quotes

String s="tutorialandexample";

Example:

String s1="tutorialandexample";  

String s2="tutorialandexample";// It doesn't create a new instance

Only one object will be created in the preceding example.

New Keyword:

String s=new String("tutorialandexample");

Example of String

public class StringExample{    
public static void main(String args[]){    
String s1="tutorial";//creating string by Java string literal    
char ch[]={'a','n','d'};    
String s2=new String(ch);//converting char array to string    
String s3=new String("example");//creating string with the help of new keyword    
System.out.println(s1);    
System.out.println(s2);    
System.out.println(s3);    
}}    

Output

What is String in Java, why it's Immutable

The code above turns a char array into a String object. And the println() function is used to display the String objects s1, s2, and s3 on the console.

What is immutable string java?

An immutable object is one whose inner property will not be change after it has been completely constructed. This indicates that once an object is committed to a variable, we can't modify the reference or the internal state in any manner. Also, we have a separate post that goes into detail about immutable objects. Read the Immutable Objects in Java page for additional details.

Why String objects are immutable in java?

Because of security, synchronization and concurrency, caching, and class loading, the String is immutable in Java. Making a string final is done to remove its immutability and prevent others from extending it.

String pool

The most common data structure is the String. Caching and reusing String variables saves a lot of memory space because they all refer to the same object in the String pool. This is precisely the purpose of the string intern pool.

The Java String Pool is a memory region dedicated to storing Strings by the JVM. Because Strings are immutable in Java, the JVM keeps the amount of memory allocated to them to a minimum by maintaining just one copy of each literal String in the pool. This is referred to as interning:

String s1 = "tutorialandexample";

String s2 = "tutorialandexample";

assertThat(s1 == s2).isTrue();

Because of the String pool's existence in the above example, two separate variables point to the same String object from the pool, conserving a critical memory resource.

Security

Security parameters, such network connections, file opening, database connection URLs, users and passwords, and so on, are likewise specified as Strings in Java. Assume that if the string is malleable, any hacker might change the value to which it refers, jeopardizing the security.

Cache of Hashcode

As is widely known, string objects are extensively used in Java. Java applications such as HashMap, HashTable, and HashSet typically use the string hashcode implementation (). The hashcode() function returns the value of a specified string object. Strings are commonly used as HashMap keys, and an immutable string assures that their value will not be changed. It means that the hashcode doesn't have to be computed every time it's used.

Performance

As we have shown, the string constant pool increases memory storage and execution. String is the most often used data structure, which improves speed.

Classloader

Furthermore, class loading makes use of parameters from the String object. Because strings cannot be altered, Classloader loads the correct class.

Synchronized

Strings are thread-safe because they cannot be changed. Assume there are multiple threads running, but none of them can be adjusted because if a thread alters the value, the String pool will produce a new String instead of modifying the old one. Synchronization is thus no longer required.

Important points

  • The untrustworthy caller method keeps the reference and can change the String between integrity checks. As a result, our query is vulnerable to SQL injections in this case. As a result, changing Strings may deteriorate security over time.
  • Another thread may likewise view the String userName and change its value after the integrity check.
  • In general, immutability helps us in this circumstance since it is easier to deal with sensitive code when values do not change because there are fewer interleavings of actions that might modify the value.

Related Topics

Java CountDownLatch

Another crucial classes for concurrent execution is CountDownLatch. It is a synchronisation tool that enables one or more threads to await until a series of tasks started by another thread...

4 minutes read.

Exception Handling in Java

Before looking at how exceptions are handled in java, it is necessary to see what an exception is. What is Exception? Whenever a program is written, errors are encountered. Some of these...

6 minutes read.

Duodecimal in Java

Duodecimal is a notation style in which a number with a base of 12 is referred to be a duodecimal number. In Java, we can use to convert duodecimal integers...

2 minutes read.

Java 13 New Features

The Java SE Platform's JDK 13 version is an open-source reference implementation defined by the Java Community's JSR 388 Process. The necessary modifications made in Java 13 are listed below....

6 minutes read.

Java Boolean toValue() Method

The valueOf() method of Java Boolean class returns a Boolean object representing the given Boolean or String value. It returns true, if the specified Boolean or string object is true...

2 minutes read.

Java Iterator

When iterating through, traversing, or retrieving the individual elements of a Collection or Flow object, a Java Cursor is leveraged as an iterator. In Java, there exist three types of...

4 minutes read.

Java String endsWith() method

Checks whether this String ends with the specified suffix or not. Syntax public boolean endsWith(String Suffix) Parameter Suffix : It takes suffix as a parameter  i.e. Sequence of characters Returns It returns true when the current...

1 minute read.

Java Math random() Method

The random() method of Math class returns a double value with a positive sign, less than 1 and greater than or equal to 0.0. This method is properly synchronized with...

1 minute read.

Java Developer

Who is a Java Developer? A Java developer is a skilled programmer who works on commercial applications, software, and webpages.  Java developers can work in two different areas: Operating system development:...

3 minutes read.

Java Enum vs Class

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four integrators named Club, Diamond,...

7 minutes read.

Java Image

For all other classes used for representing graphical images, Java's Image class serves as an abstract superclass. For images in Java, a specific form of object known as a BufferedImage...

4 minutes read.

How to Create Singleton Class in Java

In this tutorial, we will discuss the singleton class and how to create it. Introduction Java is a purely object-oriented programming language. It consists of classes and objects. But Singleton is one...

4 minutes read.

How to enable java in chrome

The Java module is huge for the Java Runtime Environment (JRE). It permits a program to work with the Java stage to run Java applets. Essentially, each of the undertakings connect...

3 minutes read.

How to set path in Java

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated Development...

5 minutes read.

Root exception in java

Java: The main feature of java which is not in C or object oriented programming language is platform independence. Not only the platform independence there are many other features in java...

3 minutes read.

Java delete directory

The File classes in Java may symbolize a directory or a file on the system. Inside the java.io package, the Files class is accessible. The File class has several helpful...

2 minutes read.

Null Pointer Exception in Java

It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants...

3 minutes read.

Java Program to print even and odd numbers using 2 threads

Using two threads in a single thread is even odd printing in Java programming with multiple threads. To create code that prints even and odd using two threads, we must...

2 minutes read.

Median Of Stream Of Running Integers in Java

An integer array is given to us. Compute the median of the elements traversed so far in the input array. For the sake of simplicity, assume that there are no...

10 minutes read.

Zig Zag star and Number Pattern in Java

We covered many Java pattern applications in the preceding part. We will write Java applications for zigzag star and number patterns in this part. Printing Zig Zag Number Pattern Steps Print one...

3 minutes read.