1

If you build an object, say "Intruder" and define it as final, you would still have the ability to change this objects fields which are not final within the class's definition (i.e Intruder.power = 50;). The restriction in that case, will be about the Intruder's object reference and not inner values.

My question is: what about Strings as an example? If you create a String object, like "String s = new String("str"); Is there a way to change the string's "str" value? If not, why is that? isn't it possible to change the literal value of that String object without changing it's reference?

Thank you!

theexplorer
  • 359
  • 1
  • 5
  • 21
  • 2
    No. The reason is actually extremely simple: String doesn't have any public fields, and it doesn't have any methods that let you change the string. (A fancy way to say this is to say it's *immutable*) – user253751 Feb 23 '15 at 02:24
  • It's because there are no public methods that allow you to change its private attributes. – Christian Tapia Feb 23 '15 at 02:26

3 Answers3

3

No there isn't because strings are immutable. When you use a method on a string it creates a new string object.

Joe
  • 337
  • 2
  • 16
  • Your answer is confusing. You can't change a string if it's immutable. – m0skit0 Feb 23 '15 at 02:29
  • 2
    His answer is correct, because you never actually change a String. When you assign a new value to a String object you're replacing it with the new value, not modifying the previous String. – deyur Feb 23 '15 at 03:09
3

Strings are immutable, as other answers have stated. StringBuilder or StringBuffer are more what you're looking for if you want the ability to alter things about the string.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
0

It is not possible. Strings are immutable, which means that they cannot be changed. If I were to do this:

String name = "John"
name.substring(2);

Nothing would happen. A new String would be returned that will never be assigned to anything.

Anonymous Person
  • 307
  • 2
  • 10