0

As far as I know a String in Java is not a primitive but an object. Java also has some shortcuts to make working with Strings easier, so that we don't have to use new String() or joining two Strings with the + operator.

So I wrote the following little test:

package programming.project.test;

public class JavaStringTests {

    public static void main(String[] args) {
        String test1 = new String("uno dos ");
        MyString test2 = new MyString("uno dos ");  

        System.out.println(test1);
        System.out.println(test2);

        extendMe(test1);
        extendMe(test2);

        //primitive-like behavior?
        System.out.println("(String) -> " + test1);

        //expected if String is not a primitive
        System.out.println("(MyString) -> " + test2);
    }


    private static void extendMe(MyString blubb) {
        blubb.add("tres ");
    }

    private static void extendMe(String blubb) {
        blubb = blubb + "tres ";
    }
}

The MyString class:

public class MyString {

    String str;

    public MyString(String str) {
        this.str = str;
    }

    public String toString() {
        return str;
    }

    public void add(String addme) {
        str += addme;
    }

}

Produces the following output:

uno dos 
uno dos 
(String) -> uno dos 
(MyString) -> uno dos tres

If String is an object, why does it automatically create a new instance of it when passed as an argument? Is String some sort of primitive-like object, something in between primitive and object?

tim-we
  • 1,219
  • 10
  • 16

2 Answers2

2

extendMe doesn't do what you think it does. Strings are immutable, they can't be changed. String.concat() doesn't change the string, it returns a new instance, which you discard in your code.

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
0
 private static void extendMe(String blubb) {
        blubb.concat("tres ");
  }

Here String.concat returns a new String with concated value.

Where as

private static void extendMe(MyString blubb) {
        blubb.concat("tres ");
}

Here you are adding the concated value to your internal str state.

Raghu K Nair
  • 3,854
  • 1
  • 28
  • 45