File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Wrapper classes not modifiable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Wrapper classes not modifiable" Watch "Wrapper classes not modifiable" New topic

Wrapper classes not modifiable

Ravi Kiran Va
Ranch Hand

Joined: Apr 18, 2009
Posts: 2234

Hi ,

I have a basic question

By definition, you may not alter the value of an immutable object after its construction.

public class Main
public static void main(String args[])

Integer i1 = new Integer(9);

i1 = 10;


Here i am able to modify the Integer value from 9 to 10 . Then Why is this called Immutable ??

Save India From Corruption - Anna Hazare.
Kevin Workman
Ranch Hand

Joined: Sep 28, 2010
Posts: 151
You aren't modifying the Object. You're modifying what Object the variable is referencing. Like this:

The actual String Objects are not changing, but what s is referencing is changing.

Read this and its follow up article to better understand what's going on.
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

Please UseCodeTags when posting code. You have been where long enough to know that. You're not changing the value of the Integer. You are reassigning the reference that will point to another Integer with a value of 10. Try making the reference final and than to change the value.

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
I agree. Here's the link:
subject: Wrapper classes not modifiable
It's not a secret anymore!