Why String is Immutable and Final in Java?

preview_player
Показать описание
Why String is Immutable and Final?:

There is hardly any Java Interview, where no questions are asked from String, and Why String is Immutable in Java is I think most popular one. This question is also asked as Why String class is made final in Java or simply, Why String is final. In order to answer these questions, Java programmer must have a solid understanding of How String works, what are special features of this class and some key fundamentals.

5 Reasons of Why String is final or Immutable in Java:

1) String Pool
Java designer knows that String is going to be most used data type in all kind of Java applications and that's why they wanted to optimize from start. One of key step on that direction was idea of storing String literals in String pool. Goal was to reduce temporary String object by sharing them and in order to share, they must have to be from Immutable class. You can not share a mutable object with two parties which are unknown to each other. Let's take an hypothetical example, where two reference variable is pointing to same String object:

String s1 = "Java";
String s2 = "Java";

Now if s1 changes the object from "Java" to "C++", reference variable also got value s2="C++", which it doesn't even know about it. By making String immutable, this sharing of String literal was possible. In short, key idea of String pool can not be implemented without making String final or Immutable in Java.

2) Security:
Java has clear goal in terms of providing a secure environment at every level of service and String is critical in those whole security stuff. String has been widely used as parameter for many Java classes, e.g. for opening network connection, you can pass host and port as String, for reading files in Java you can pass path of files and directory as String and for opening database connection, you can pass database URL as String. If String was not immutable, a user might have granted to access a particular file in system, but after authentication he can change the PATH to something else, this could cause serious security issues. Similarly, while connecting to database or any other machine in network, mutating String value can pose security threats. Mutable strings could also cause security problem in Reflection as well, as the parameters are strings.

3) Use of String in Class Loading Mechanism

4) Multithreading Benefits
Since Concurrency and Multi-threading was Java's key offering, it made lot of sense to think about thread-safety of String objects. Since it was expected that String will be used widely, making it Immutable means no external synchronization, means much cleaner code involving sharing of String between multiple threads. This single feature, makes already complicate, confusing and error prone concurrency coding much easier. Because String is immutable and we just share it between threads, it result in more readable code.

5) Optimization and Performance
Now when you make a class Immutable, you know in advance that, this class is not going to change once created. This guarantee open path for many performance optimization e.g. caching. String itself know that, I am not going to change, so String cache its hashcode. It even calculate hashcode lazily and once created, just cache it. In simple world, when you first call hashCode() method of any String object, it calculate hash code and all subsequent call to hashCode() returns already calculated, cached value. This results in good performance gain, given String is heavily used in hash based Maps e.g. Hashtable and HashMap. Caching of hashcode was not possible without making it immutable and final, as it depends upon content of String itself.

~~~~Subscribe to this channel, and press bell icon to get some interesting videos on Selenium and Automation:

Follow me on my Facebook Page:

Let's join our Automation community for some amazing knowledge sharing and group discussion on Telegram:

Рекомендации по теме
Комментарии
Автор

Note: From Java 7 onwards, the Java String Pool is stored in the Heap space.

punitdixit
Автор

thanks for your time naveen...we r very much thankful towards your work

anilleo
Автор

This is the best explanation. Nobody can match you. Thanks

jagadeeshbaskaran
Автор

Important note: Java String Constant Pool is created inside Heap area.

ashishgoswami
Автор

Hi, I doubt Why strings are called immutable, because if give like this String s="hi" and in the next line, we give s="hello" the value of s will change right please help me to understand anyone.

qwertkeys
Автор

It would be great to see more code examples, specially tricky ones. There is 20 minutes of explanation with simple examples but some questions on tests are much trickier and students still fall into the trap.

lamberto
Автор

Hi Naveen,

Thanks for spending so much time while creating the knowledge.

I am still in doubt on immutability, to me, it seems every variable is immutable:

String s1 = "Java";
String s2 = "Java";
String s3 = s1;

s3 = "NewJava";

System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s1);

int i1 = 10;
int i2 = i1;
i2=20;

System.out.println(i1);

Integer i3 = 30;
int i4 = i3;
i4 = 40;

System.out.println(i3);

rxpzrmo
Автор

Thanks Naveen for sharing. God bless you.

astuteacerbic
Автор

Hi Naveen,
Can you make video on Role & Responsibility of tester in AWS cloud computing. much needed

USP
Автор

I don't want to start some East-Coast/West-Coast Gangster Rap War here, but I did notice something. On the answer given by Naresh i Technologies channel here on YouTube, they emphasize very much something that you don't, and mention these only in passing. Some viewers angrily suggested that the "Real Reasons" were what you show here. However, while everything in here is true, I think there is a second reason that was there from the very beginning and became even more important over time and is what is emphasized by Hari Krishna in his video:
Suitability of the very common data types of Sting/Integer/other wrapper classes as keys in Hashtable objects, and later HashMap objects, and also later members of SortedSet/NavigableSet or keys of SortedMap objects. His presentation suggests that this was primary and the other things all good, but came later. Anyway, you do highlight why final is necessary for these classes even tho there are plenty of times one wishes one could subclass them for legitimate and honorable purposes, the security danger is too great. Cheers.

jvsnyc
Автор

what happen when we declare like
String s = new String("tejas");
String s1 = new String("toley");
is the ref. stored in heap memory?

tejastoley
Автор

Can you please give me the Java tutor for Selenium that you have in your video. Couldn't find the right link.

Thanks

bikashdeuja
Автор

Awesome Video, Can you please make one video on this program -> "You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array. Traverse array only once". I encountered this question in of the interviews I gave.
Thanks in Advance

sparshpandey
Автор

How can I have live chat with you to discuss about selenium/java If I became the member of this?

shanthikandasamy
Автор

Hi naveen anna, can u make any videos on selenium with c# atleast some advanced videos like framework level

venkateshandea
Автор

Hi naveen please make some videos on protractor, it will be very helpful

vivekkurhe
Автор

awsome naveen bro.nice way of telling....👌

gnsc
Автор

hi bro, if we create strings in non-constant loop like String s1=new String("java"); then how string is immutable, please kindly explain it

nukalasagar
Автор

one confusion sir
immutable String value are change value or not change

omashete
Автор

my question is regarding Xpath ... as u said in drop down session like By.id() in main()... but wen v separately save xpaths in .propertiesfile and wen v want to automate that through keywords.java class den how to use it ...
public void choose(String objectname, String data)
{
Select select = new
// ???
}



???

priya-vfjc