Immutable String in Java

Yes, the Strings are immutable in java. Immutable means static that is unmodifiable or unchangeable. Once we create the string object then we are unable to change its data. But we can create a new staring.

For example:
class Immutablestring{
 public static void main(String args[]){
    String a="Java";
     a.concat("program"):// concat is a string method
     System.out.printIn(a);
 }
}

Output:

Java 

Why string is immutable in java?

Let’s talk about some string features, that will help us in understanding why string is immutable in java.

  • String pool is possible only because String is immutable in Java. This way Java Runtime saves a lot of heap space because different String variables can refer to the same string variable in the pool. If String would not have been immutable, then String interning would not have been possible because if any variable would have changed the value, it would have been reflected in the other variables too.
  • Serious threats in an application can b occur if the string is not immutable. For example, database username, the password is passed as String to get database connection and in socket programming host and port, details passed as String. Because String is immutable, its value can’t be changed otherwise any hacker could change the value.
  • it is safe for multithreading. A single string instance can share different threads. This keeps away the use of synchronization for thread safety. Strings are implicitly thread-safe.
  • Since String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for the key in a Map and its processing is faster than other HashMap key objects. This is why String is the most widely used as HashMap keys.

Recommended Posts:

Difference between the Java and JavaScript

What is JavaScript?

How are java objects stored in memory?

Compilation and Execution of a java program

References:

www.javatpoint.com

www.journaldev.com

Leave a Reply

Your email address will not be published. Required fields are marked *