Issue
In java, strings are immutable, so when i declare an instance String variable i can't chang its value in class level scope, however i amable to change its value inside a method, why?
public class AnotherBasic {
String p ="Bye";
p = "nknk";
public void testttt() {
System.out.println(p);
p = "5656";
System.out.println(p);
}
public static void main(String[] args)
{
AnotherBasic ab = new AnotherBasic();
ab.testttt();
}
}
At "p = "ncinci" " throws me an error but It happily changes the value of p inside testttt() method. Why and How?
Solution
I think you might have a slight misunderstanding of the immutability concept.
Let's say your String
variable greeting
is [H, E, L, L, O]
.
If you wanted to change your greeting
, you can't add other letters or remove them from your word, like eg. greeting.add(O)
to make it [H, E, L, L, O, O]
, because you can't change it's content, so it's immutable
The only way to change it is to make it so when you think about your greeting
you think about a whole another word like [W, H, A, T, S, U, P]
, this means that you didn't change the HELLO
word, you are just using another one.
Answered By - ndriqa
Answer Checked By - Marie Seifert (JavaFixing Admin)