Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Wrapper classes not modifiable

 
Ravi Kiran Va
Ranch Hand
Posts: 2234
Eclipse IDE Firefox Browser Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
System.out.println(i1);

}
}


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


 
Kevin Workman
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic