Difference of use of immutable object in method argument or outside it

Asked

Viewed 64 times

2

If I have the following String of which it was created:

String s1 = "Primeira String";

When using the method:

s1.toUpperCase();

nothing happens because an instance has been created and has not been assigned to any variable.

But if I roll:

System.out.println(s1.toUpperCase());

I see the result in capital letters, what is the difference of these cases?

1 answer

5


The difference is only that one you do not see and the other you see, nothing else. The difference is the method println().

nothing happens

Wrong premise.

at this time a

Contradicts the premise.

The first creates the new instance and nothing else can be done with it. It cost to create, occupied memory and will remain there until the object is collected. The second code passes this object through a reference to the method println() do what he knows how to do, then potentially have a lifespan guaranteed a little higher, but in practice we know that it does not matter in a simple example, the object will only be available for an instant in its creation and execution of the method.

In fact the problem itself has nothing to do with the fact that the object is immutable, that is circumstantial, any object that was created would occur the same.

Perhaps it lacks understanding of what a variable, She’s simpler than people realize.

  • Your first phase clarified for me rsrs, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.