1.

Why Strings in Java are Immutable?

Answer»

Strings in Java are immutable. This means that they are unchangeable or unmodifiable. There are several reasons for this. Some of these are given below:

  • Synchronization and Concurrency

Synchronization issues are solved by making strings in Java as immutable. This is  because they automatically become thread safe if they are immutable.

  • Class Loading

Class Loading has string arguments. If Strings were MUTABLE, then wrong classes could be loaded as mutable objects change their state.

  • Security

Network connections, urls, DATABASE connections, usernames/passwords etc. have parameters that are represented as String. These parameters could be easily changed if the Strings were mutable and that WOULD be a security breach.

A program that demonstrates Strings is given as FOLLOWS:

public class Demo {   public static void main(String args[]) {     String str = "Snow";     str.concat("White");     System.out.println(str); }   }  

The output of the above program is as follows:

Snow

In the above program, only Snow is printed as Strings are immutable objects.



Discussion

No Comment Found