Swap two strings in Java, by passing them to a utility function, but without returning objects or using wrapper classes

前端 未结 9 2247
既然无缘
既然无缘 2020-12-16 20:31

I am trying to swap two strings in Java. I never really understood \"strings are immutable\". I understand it in theory, but I never came across it in practice.

Also

9条回答
  •  爱一瞬间的悲伤
    2020-12-16 20:58

    Basically, you cannot implement swap method in Java.

    The reason you cannot do this is that Java argument has pass-by-value argument semantics. So when your swap method assigns s2 to s1 and so on, it is operating entirely on the local variables s1 and s2, and NOT on the s1 and s2 variables in the calling method main.

    By contrast, if you were to implement the swap method in C, it would look something like this:

    void swap(char ** s1, char ** s2) {
        char * temp = *s1;
        *s1 = *s2;
        *s2 = temp;
    }
    

    and you would call it like this:

    char *s1 = "Hello World";
    char *s2 = "Goodbye World";
    swap(&s1, &s2);
    

    Notice that we are actually passing the address of a "pointer to char" variable.

    In Java, you cannot do this because you cannot take the address of a variable. It is simply not supported.

提交回复
热议问题