I was reading through Item 15 of Effective Java by Joshua Bloch. Inside Item 15 which speaks about \'minimizing mutability\' he mentions five rules to make objects immutable. On
String
is immutable because as far as its users are concerned, it can never be modified and will always look the same to all threads.
hashCode()
is computed using the racy single-check idiom (EJ item 71), and it's safe because it doesn't hurt anybody if hashCode()
is computed more than once accidentally.
Making all fields final is the easiest and simplest way to make classes immutable, but it's not strictly required. So long as all methods return the same thing no matter which thread calls it when, the class is immutable.