-3

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

String a = "Vehicle";
1
  • Do you want to say that though String objects are immutable how can we achieve String a = "Vehicle"; a = "New " + a; ? Commented Apr 23, 2015 at 9:24

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
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.
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
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.