Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

Why string is immutable or final in java? What are the benefits of immutable object?

user-image
Question added by Mohd shahnawaz khan , Associate Project , Cognizant Technology Solution
Date Posted: 2013/09/01
Advaitha Chidurala
by Advaitha Chidurala , Teacher , Little Masters Abacus

String class is immutable. Its so because u will be having a number of reference variables pointing to single object, iff the object content is same of  all those references variables..so if user tries to change or modify the content of the String..then this will be affecting all other reference variables pointing to the object. So this is the reason why String class is immutable.

This results in saving a lot of memory space as a no.of references variables can point to a single object if the content is same.

 

sudha reddy
by sudha reddy , Senior Software Engineer , Virtusa Consulting Services Hyderabad

security reasons:

for opening network connections,you can pass host name,url as string

you can open any file in java by passing name of file as argument to File I/O classes.if string is not immutable this would lead serious security threat , I mean some one can access to any file for which he has authorization, and then can change the file name either deliberately or accidentally and gain access of those file.

Munir Bahaderi
by Munir Bahaderi , Project Engineer , NourNet

Some of the important reasons are:

  1. Security: for example, openning a file by name takes string argument for the file name. If string is not immutable, a person who has access to a certain file name, can gain access to other files by changing the name string.
  2. Immutable objects are simple since they only have1 state to represent.
  3. Immutable object are thread-safe inherintly, so they don't nead synchornization in multi-threaded programs

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.