-3

I'm new to java programming. And I don't understand why string objects are immutable in java.

String a = "Vehicle";
  • Do you want to say that though `String` objects are immutable how can we achieve `String a = "Vehicle"; a = "New " + a;` ? – Blip Apr 23 '15 at 09:24

1 Answers1

0

Because java uses the concept of string literal. Suppose there are five reference variables, all refers to one object "Vehicle".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

Dhanuka
  • 2,826
  • 5
  • 27
  • 38
  • Well, that's *one* reason. It would be feasible for there to be "read-only" strings, or copy-on-write for literals etc. There are other reasons for strings to be immutable. – Jon Skeet Apr 23 '15 at 09:21
  • It is a design choice for the sake of safety: if I hold a reference to a ```java.lang.String``` object I'm sure no other process will alter its contents. – Ramón Gil Moreno Apr 23 '15 at 09:23
  • Should I post every reason for this answer. I posted what I know as an answer. And I believe I posted a correct answer for his/her question. @JonSkeet – Dhanuka May 26 '15 at 03:44
  • As I said before, it would be entirely reasonable for Java have been designed a different way - being able to pool literals is one efficiency benefit of using immutable strings, but if immutability was a generally bad idea for strings, we just wouldn't do that. There are *much* better reasons for strings being immutable. – Jon Skeet May 26 '15 at 05:18