File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Why are all primitive wrappers immutable? <eom> Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Why are all primitive wrappers immutable? <eom>" Watch "Why are all primitive wrappers immutable? <eom>" New topic
Author

Why are all primitive wrappers immutable? <eom>

C Shinde
Ranch Hand

Joined: Oct 22, 2009
Posts: 60
Why are wrappers like Integer, Double and String immutable?

Thanks in advance.


Regards,
Chetan Shinde
pawan chopra
Ranch Hand

Joined: Jan 23, 2008
Posts: 326

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.


Pawan Chopra
SCJP - DuMmIeS mInD
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 26710
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
  •  
     
    subject: Why are all primitive wrappers immutable? <eom>
     
    Threads others viewed
    Filters
    A Question about Wrapper class
    Object creation for Integer class
    When the JVM create a new Wrapper and when the JVM use a living one? ( K&B 5.0)
    why string
    Two Laptop Bag

    cast iron skillet 49er

    more from paul wheaton's glorious empire of web junk: cast iron skillet diatomaceous earth rocket mass heater sepp holzer raised garden beds raising chickens lawn care CFL flea control missoula heat permaculture