This Java tutorial says that an immutable object cannot change its state after creation.
java.lang.String
has a field
/** Cache the hash code for the string */
private int hash; // Default to 0
which is initialized on the first call of the hashCode()
method, so it changes after creation:
String s = new String(new char[] {' '});
Field hash = s.getClass().getDeclaredField("hash");
hash.setAccessible(true);
System.out.println(hash.get(s));
s.hashCode();
System.out.println(hash.get(s));
output
0
32
Is it correct to call String
immutable?
Java String Pool is the special memory region where Strings are stored by the JVM. Since Strings are immutable in Java, the JVM optimizes the amount of memory allocated for them by storing only one copy of each literal String in the pool.
The String is immutable in Java because of the security, synchronization and concurrency, caching, and class loading. The reason of making string final is to destroy the immutability and to not allow others to extend it. The String objects are cached in the String pool, and it makes the String immutable.
In Java, C#, JavaScript, Python and Go, strings are immutable.
Other objects are mutable: they have methods that change the value of the object. String is an example of an immutable type. A String object always represents the same string.
A: The answer to your question is simple: once an Integer instance is created, you cannot change its value. The Integer String , Float , Double , Byte , Long , Short , Boolean , and Character classes are all examples of an immutable class.
A better definition would be not that the object does not change, but that it cannot be observed to have been changed. It's behavior will never change: .substring(x,y)
will always return the same thing for that string ditto for equals
and all the other methods.
That variable is calculated the first time you call .hashcode()
and is cached for further calls. This is basically what they call "memoization" in functional programming languages.
Reflection isn't really a tool for "programming" but rather for meta-programming (ie programming programs for generating programs) so it doesn't really count. It's the equivalent of changing a constant's value using a memory debugger.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With