0

Why does the following code print "1234" rather than "welcome"?I think that String is not a primitive variable,it is an object.So the function "changeStr" get the reference of "str".But the fact is seem like "changeStr" get a copy of the str.Why?

public class Test1 { 
    public static void changeStr(String str){
        str="welcome";
    }
    public static void main(String[] args) {

        String str="1234";
        changeStr(str);
        System.out.println(str);
    }
}
surrey
  • 53
  • 4
  • from the docs:" String objects are immutable, which means that once created, their values cannot be changed. The String class is not technically a primitive data type, but considering the special support given to it by the language, you'll probably tend to think of it as such. You'll learn more about the String class in Simple Data Objects" – Oren Yosifon Dec 19 '15 at 15:49
  • 4
    @OrenYosifon It has nothing to do with immutability here. – Alexis C. Dec 19 '15 at 15:53
  • 1
    @Alexis C. It's not even related to pass by reference or value.How come its a duplicate? – Mathews Mathai Dec 19 '15 at 15:55
  • 2
    @MathewsMathai So it's related to what in your opinion? – Alexis C. Dec 19 '15 at 15:57
  • 1
    @Alexis C. His question is why is it not printing welcome?...It's a logical error.He has not returned the changed value...and he hasn't even assigned it to str.. – Mathews Mathai Dec 19 '15 at 15:58
  • 2
    @MathewsMathai I think you didn't understand the question and the assumption made by the OP here. – Alexis C. Dec 19 '15 at 16:00
  • @Alexis C. His logic itself is wrong.The other questions wouldn't let him know the logical errors he has done. – Mathews Mathai Dec 19 '15 at 16:01
  • 1
    @MathewsMathai The duplicate explains exactly why it doesn't print "welcome", and this question is all about it. It's obvious from the code of this question what the OP expected by doing `str="welcome";` with the method returning nothing. I don't know why I'm still trying to argue... – Alexis C. Dec 19 '15 at 16:05
  • @Alexis C. So sorry.I got it cleared!! – Mathews Mathai Dec 19 '15 at 16:13

0 Answers0