Thursday, September 3, 2009

Are Strings really immutable?

From java Basic String Class is immutable.But actually speaking String is not immutable.This is due to lack of security in String Class.Therefore you can change it using Reflection Concepts.
e.g:
Normal :
String lc = "lowercase";
lc.toUpperCase();
System.out.println(lc);
Now it may look immutable.But you can modify it with the following snippet:
Field stringValue = String.class.getDeclaredField("value");
stringValue.setAccessible(true);
stringValue.set(orig, orig.toUpperCase().toCharArray());

This is because of SecurityManager is not turned on.Though
you have an immutable class it is mutable unless the security manager
is turned on.

2 comments:

  1. @anai. Your post was very informative. It would be more interesting if you would just give us a usecase where immutability is really important. In real world usecases, i think the final access qualifier should be able to staisfy our need since we will be abstracting already abstract objects. So can you give us a use case where immutability will be really put into use

    ReplyDelete
  2. N hw do i turn on the security manager??

    ReplyDelete