• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why are all primitive wrappers immutable? <eom>  RSS feed

 
C Shinde
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why are wrappers like Integer, Double and String immutable?

Thanks in advance.
 
pawan chopra
Ranch Hand
Posts: 419
jQuery Mac Objective C
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have got following stuff from net:



The main reason why String made immutable was security.

Look at this example: We have a file open method with login check. We pass a String to this method to process authentication which is necessary before the call will be passed to OS. If String was mutable it was possible somehow to modify its content after the authentication check before OS gets request from program then it is possible to request any file. So if you have a right to open text file in user directory but then on the fly when somehow you manage to change the file name you can request to open "passwd" file or any other. Then a file can be modified and it will be possible to login directly to OS.




I am not sure about it but basically these are value Objects and you would use them as values not as reference. I hope you will get much better answers here.
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you should consider whether any class can be made immutable. Look at the design of java.awt.Point. A mutable class with public fields. A disaster to try to synchronise. Immutability carries all sorts of advantages, for example:
  • No need to clone or copy
  • Thread safety
  •  
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!