This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
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


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
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: 362

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: 32675
    
    4
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
  •  
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Why are all primitive wrappers immutable? <eom>
     
    Similar Threads
    Filters
    A Question about Wrapper class
    Object creation for Integer class
    why string
    When the JVM create a new Wrapper and when the JVM use a living one? ( K&B 5.0)