String in Java is object, so it should be reference?

This question already has an answer here:

  • Is Java “pass-by-reference” or “pass-by-value”? 79 answers

  • 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

    链接地址: http://www.djcxy.com/p/20888.html

    上一篇: 编译器:如何实现引用计数(在简单的VM中)

    下一篇: Java中的字符串是对象,所以它应该是引用?