As far as I know, Java only knows call by value. This means, for primitive data types, you will work with ana copy, and for objects you will work with an copy of the reference to the objects. However, I think there are some pitfalls; for example, this will not work:
public static void swap(StringBuffer s1, StringBuffer s2) {
StringBuffer temp = s1;
s1 = s2;
s2 = temp;
}
public static void main(String[] args) {
StringBuffer s1 = new StringBuffer("Hello,");
StringBuffer s2 = new StringBuffer("World!");
swap(s1, s2);
System.out.println(s1);
System.out.println(s2);
}
This will populate "Hello, World!" and not "World!" "Hello," because in the swap function you use copies which don't have any impact on the references in the main. But if your objects are not immutable, you can change it. For example:
public static void appendWorld(StringBuffer s1) {
s1.append(" World!");
}
public static void main(String[] args) {
StringBuffer s = new StringBuffer("Hello,");
appendWorld(s);
System.out.println(s);
}
This will populate "Hello, World!" on the command line. If you change StringBuffer into String, it will produce just "Hello, " because String is immutable. For example:
public static void appendWorld(String s){
s = s+" World!";
}
public static void main(String[] args) {
String s = new String("Hello,");
appendWorld(s);
System.out.println(s);
}
However, you could make a wrapper for String like this which would make it able to use it with Strings:
class StringWrapper {
public String value;
public StringWrapper(String value) {
this.value = value;
}
}
public static void appendWorld(StringWrapper s){
s.value = s.value +" World!";
}
public static void main(String[] args) {
StringWrapper s = new StringWrapper("Hello,");
appendWorld(s);
System.out.println(s.value);
}
Edit: I believe this is also the reason to use StringBuffer when it comes to "adding" two Strings, because you can modifiemodify the original object which uyou can't with immutable objects like String is.