Friday, 5 August 2016

Java String not behaving like an object?

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?

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...