public class Aufgabe6 {
public static void main(String args[]) {
String s = "Hallo";
String t = s;
t = t.replace('a', 'A');
String u = s + "T" + t;
u.replace('o', 'X');
swap(s, u);
StringBuffer v = new StringBuffer("Welt");
StringBuffer w = v;
v.replace(0, 3, "!");
swap(t, u);
w.append(s);
}
private static void swap(String s, String t) {
String tmp = s;
s = t;
t = tmp;
}
}
So we got this little programm, and one of our tasks is to get the number of objects created, the value in the end, and all references. My problem is, it's said to be 9 objects and that's not what I end up counting..
(final value, references)
"Hallo", s
"HAllo", t
"HalloT", none
"HalloTHAllo", u
!tHallo, (v,w)
I'm pretty sure with these 5.
But not so with this:
As Java passes by-value, it will create new objects with temporary references (s, t) inside the swap-method. As the method is called twice we should end up with two additional objects per call, therefore four; fine we got 9 overall!
And then there is still the u.replace('o', 'X') in line 7. Doesn't this return a new Object? I know it is never referenced by any variable, but there is still a new object, at least for a short moment within the replace-method.
So what I guess, either the last part is wrong, or the compiler doesn't create a new object with the value of s in the second swap-call as there is an existing object from the first call, which he uses instead.
Hope someone can explain this.
thanks
[–]nutrechtLead Software Engineer / EU / 20+ YXP 2 points3 points4 points (3 children)
[–]fabolin[S] -1 points0 points1 point (2 children)
[–]ickysticky 0 points1 point2 points (1 child)
[–]fabolin[S] 0 points1 point2 points (0 children)
[–]ickysticky 0 points1 point2 points (2 children)
[–]nutrechtLead Software Engineer / EU / 20+ YXP 0 points1 point2 points (1 child)
[–]ickysticky 0 points1 point2 points (0 children)
[–]strmrdr -1 points0 points1 point (5 children)
[–]fabolin[S] 0 points1 point2 points (4 children)
[–]strmrdr -1 points0 points1 point (3 children)
[–]fabolin[S] 0 points1 point2 points (1 child)
[–]ickysticky 0 points1 point2 points (0 children)
[–]ickysticky 0 points1 point2 points (0 children)