×

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

Perfect Number Program in Java

Perfect Number Program in Java A perfect number is a number whose sum of all the factors, excluding the number itself, is equal to the number. For example, 28 is a...

4 minutes read.

Math fma () method in java

In java, the Math module constitutes of fma () Method in it. This method can be accessed in two ways which can be differentiated by the parameters which are given...

4 minutes read.

Java Code Coverage Tools

Code coverage testing is a crucial metric that gauges how thoroughly the program's source code has been tested. The market is flooded with Code Coverage Tools, making it difficult to...

7 minutes read.

Collection Programs in Java

Collection Programs in Java Collection in Java provides a way to manipulate or store a group of objects. Each object in a collection is called element. Collection programs in Java mainly...

4 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

Synchronized Keyword in Java

Synchronization is the process of limiting access to a shared resource or data to a single thread at a given moment in time. This aids in shielding the data from...

6 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

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 Session

Session indicates interval of time. A session is a simple  time interval in which servers and client interacts. To maintain the state of the client or user we use technologies...

5 minutes read.

Object Oriented Programming (OOPs)

Since the dawn of earth, we have kept on evolving. The need for evaluation comes with the aim of improving the existing systems when something inappropriate is found for the...

5 minutes read.

Java Integer divideUnsigned() method

The divideUnsigned() method of Integer class returns the unsigned quotient by dividing the first argument by the second argument. Syntax public static int divideUnsigned (int dividend , int divisor) Parameters The parameter ‘dividend’ represents...

1 minute read.

Java Technologies List

Introducing Java technology is not necessary. Everyone across the globe is still in awe of Java's incredible capabilities for developing mobile apps and websites. Of course, you can be persuaded...

8 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

Java Numbers

We use primitive data types like byte, int, long, double, etc to work with the numbers, When we need objects, we use wrapper class like Integer, Double, Long, Byte, etc....

2 minutes read.

How to use scanner in Java

Scanner class in Java is the part of java.util package. Java programming language has various ways to read input from the user, Scanner class is one of the classes to...

5 minutes read.

Mutable class in Java

A language for object-oriented programming is Java. Because this is an object-oriented language of programming, all of its mechanisms and methods are based on objects. Java has a concept of...

6 minutes read.

How to Send SMS in Java with Example

Sending SMS messages in Java is a fairly common task, and there are a number of libraries and APIs available to help you do it. One popular option is to...

2 minutes read.

How Many Ways to Create an Object in Java?

As you know, a class is a blueprint for an object, and you can create objects from it. There are several ways to create objects of classes in Java. This...

6 minutes read.

Set Matrix Zeros in Java

In coding round interviews, it is frequently asked as the most significant challenge. an m*n matrix is provided. Set the entire column and row of the matrix to 0 if any...

6 minutes read.

Java Boolean booleanValue() method

The booleanValue() method of Java Boolean class returns a Boolean value for the specified Boolean argument. Syntax public Boolean booleanValue() Parameters NA Return Value This method returns the primitive value of specified Boolean object. Example 1 public class...

2 minutes read.