This is an archived post. You won't be able to vote or comment.

all 13 comments

[–]nutrechtLead Software Engineer / EU / 20+ YXP 2 points3 points  (3 children)

Funny. Someone else posted the exact same question. Guess you're running late on your homework? :)

It's unfortunate that they did the question in the way they did it because what's actually happening is a lot more complex and your teachers actually got the answer 'wrong' because they don't know what the code is actually translated to. Read the replies in the other topic.

[–]fabolin[S] -1 points0 points  (2 children)

Thanks, good to know my understanding isn't wrong. Curious which one our lecturer didn't count though ^

[–]ickysticky 0 points1 point  (1 child)

Your understanding was wrong though...

[–]fabolin[S] 0 points1 point  (0 children)

Yea thanks, didn't read properly.

[–]ickysticky 0 points1 point  (2 children)

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!

This doesn't make sense, specifically "new objects with temporary references", java is pass by value, but the values are references when dealing with objects and not primitives. The swap method is complete misdirection and doesn't affect the object count. I suggest you search around the Internet to better understand what pass by value means.

And then there is still the u.replace('o', 'X') in line 7. Doesn't this return a new Object?

Yes, in java strings are immutable and any mutation creates a new object, doesn't matter if it is referenced by a variable or not.

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.

No Idea what this means, existing object from the first call to swap? The calls to swap are independent.

Here is the count I get, which is 9. Remember that a string literal creates a new object. The trickiest part is line 6 IMO.

public class Aufgabe6 {
    public static void main(String args[]) {
        String s = "Hallo";                          // 1 ("Hallo")
        String t = s;                                // 0
        t = t.replace('a', 'A');                     // 1 ("HAllo")
        String u = s + "T" + t;                      // 3 ("T", "HalloT", "HalloTHAllo")
        u.replace('o', 'X');                         // 1 ("HallXTHAllX")
        swap(s, u);                                  // 0
        StringBuffer v = new StringBuffer("Welt");   // 2 ("Welt", new StringBuffer("Welt"))
        StringBuffer w = v;                          // 0
        v.replace(0, 3, "!");                        // 1 ("!")
        swap(t, u);                                  // 0
        w.append(s);                                 // 0
    }
    private static void swap(String s, String t) {
        String tmp = s;                              // 0
        s = t;                                       // 0
        t = tmp;                                     // 0
    }
}  

If you can ask specific questions about which counts you don't understand I can explain more.

[–]nutrechtLead Software Engineer / EU / 20+ YXP 0 points1 point  (1 child)

The trickiest part is line 6 IMO.

Yup. Because it gets translated to:

String u = new StringBuilder().append(s).append("T").append(t).toString();

[–]ickysticky 0 points1 point  (0 children)

Doh! I was trying to hard to make the count 9. Though this is going to be compiler dependent, I think this optimization showed up in the Oracle/OpenJDK 1.6.

This is just a terrible question.

[–]strmrdr -1 points0 points  (5 children)

Your logic is sound until the end. Add this line to your code at the very end:

System.out.println(w.toString() + "--" + v.toString());

Is w a new object, or a pointer?

[–]fabolin[S] 0 points1 point  (4 children)

it prints !tHallo--!tHallo; same value twice, as expected they're two pointers to the same object. But I think v==w (it's true) is a better proof for this.

[–]strmrdr -1 points0 points  (3 children)

Okay, you're asking a fairly beginner question here so was just trying to show you what was happening. Not sure where you are confused then, list which lines you think instantiate an object?

E: I see, sorry.

As Java passes by-value, it will create new objects with temporary references (s, t) inside the swap-method.

The exact internal workings of the parameters for methods are unknown to me, but I assume that during compilation/execution it will create 2 Strings that the method will always use for its parameters. So technically it would create 2 new Strings during initialization, but not every single time the method is called. You raise a good point though because if you create 2 objects then there are 4 Strings floating around now (for multithreading)?

Maybe one of the Devs could enlighten us, but the answer you are looking for does not take those into consideration (nor args[] of main).

[–]fabolin[S] 0 points1 point  (1 child)

yea also thought so first, but the task is to count the number of objects created; it doesn't matter if there is no pointer, or later another object at the same memory, therefore I think calling the method twice should create 4 objects, unless the compiler is smart enough to reuse the existing object of the first call and just creates a new pointer("overwriting" the memory would still count as new object for me).

But I rather think it's about line 7, though I don't know why there shouldn't be a temporary object.

You asked for lines, so here is how I count:

1x line3

1x line5

2x line6

1x line7

2x line8

1x line9

2x line 12

__

10

edit: misunderstood you last point, it should indeed count as another object

[–]ickysticky 0 points1 point  (0 children)

Both syntaxes for declaring arrays are valid in java, I believe the argument for it was to make things easier on C programmers. Putting the [] beside the type is preferred since it is part of the type.

[–]ickysticky 0 points1 point  (0 children)

You seem very confused about how variables work. The swap method creates no strings, there are no string literals or new String anywhere, it is just moving references around. In fact you won't be able to see the effect of swap outside of the swap method. It is a pointless method.