String in Java is object, so it should be reference?
This question already has an answer here:
The object's reference is passed to the method and assigned to the parameter, which is a kind of local variable.
Assigning a different object reference to the parameter does nothing to the variable outside the method that held a reference to the original object.
Also String is immutable, so there's no way to change its value (for example a setValue()
method).
The line str = "welcome";
doesn't change the value of any String - Strings can never change their values. What it does is it makes one reference point to a different String. But the reference that it reassigns is the one that's local to changeStr
, not the one that is declared in main
.
String is a reference, but the key is that String str
inside changeStr
is a different reference than str
in main. Add that to the fact that strings are immutable in Java (meaning that when you change a String, the reference points to a different location in memory) and that explains why main will print 1234