Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it correct to call java.lang.String immutable?

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?

like image 594
Evgeniy Dorofeev Avatar asked Mar 07 '13 15:03

Evgeniy Dorofeev


People also ask

Is Java Lang 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.

Why is Java String called immutable?

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.

Which language String is immutable?

In Java, C#, JavaScript, Python and Go, strings are immutable.

Is String is immutable yes or no?

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.

Does Java Lang integer define immutable objects?

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.


1 Answers

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.

like image 103
Sled Avatar answered Oct 07 '22 17:10

Sled