Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

I am used to doing the following in C:

void main() {

    String zText = "";

    fillString(zText);

    printf(zText);

}

void fillString(String zText) {

    zText += "foo";

}

And the output is:

foo

However, in Java, this does not seem to work. I assume because the String object is copied instead of passed by referenced. I thought Strings were objects, which are always passed by reference.

What is going on here?

1 Answer

0 votes
by (46k points)

In Java nothing is passed by reference. Everything is passed by value. Object references are passed by value. Additionally Strings are immutable. So when you append to the passed String you just get a new String. You could use a return value, or pass a StringBuffer instead.

Related questions

Browse Categories

...