• Post Reply Bookmark Topic Watch Topic
  • New Topic

String class is not immutable since we are able to re-assign another value to same String variable  RSS feed

 
kavitha Jayachandran
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public static void main(String[] args) {
String str1="Java";
str1="one";
System.out.println("str1="+str1);
}

As per book OCA Java SE7 certification guide by Mala Gupta,
String object is stored in a private final char array in String.java.
private final char value[];
The basic characteristic of a final variable is that it can initialize a value only once. By
marking the variable value as final, the class String makes sure that it can’t be reassigned
a value.

so the String objects can be initialized only once but the above code shows that str1 was initialized first with "Java", then it can be re-assigned value "one" bcos the output is one. If it can be re-initialized, basic characteristic of final variable is not satisified and hence how can we call String objects are immutable?
 
Tushar Goel
Ranch Hand
Posts: 934
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it means you can't change the value of the string. You can't modify or append the string "Java" or "one". It will create a new object if you are trying to do.

example:

String str1 = "Java"
String str2 = "one"
String str1 = str1 + str2

Then it will create a new object and assign the reference to the str1 but don't modify existing one.
 
Carey Brown
Saloon Keeper
Posts: 3310
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
kavitha Jayachandran wrote:so the String objects can be initialized only once but the above code shows that str1 was initialized first with "Java", then it can be re-assigned value "one" bcos the output is one. If it can be re-initialized, basic characteristic of final variable is not satisified and hence how can we call String objects are immutable?

"str1" is not, itself, a String, it is a reference to a String. You can change String references all you like but not the content of the String that the reference refers to.
 
kavitha Jayachandran
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the replies. I undertstand that str1 is just a reference to the string so it can be re-assigned but the actual String referred to by str1 which is "Java" cannot be modified and is immutable.
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Correct
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!