Wednesday, September 14, 2016

JAVA 22 - Methods aren't always pass by value

Well - I thought we were done!  The funny thing about learning, you never really are done.

Today before leaving, I have a conversation with one of our new developers who's learning Java about passing values to methods.

We covered this back a way ago here, where we passed primitive data types, and could see if we changed the value in the method, it didn't affect the value passed, because primitives are passed by value.  You can find the exact code on Github here.

My developer, David, was looking at this item on StackOverflow (it's a great source of information and worked-through problems, which always comes up in any Google search).

That example given seemed to be saying that if you pass an object, rather than just a primitive data type (integer, String etc), then you are passing the object by reference.  This means that any changes you make the to item you've been passed get made to the original object itself - you are NOT creating a copy as with primitive variables.

Even our more experienced developer was sure this was wrong.  I managed to talk them into looking at it from my perspective, in the only way that really matters - let's build it and find out!

We have the following simple dogClass to keep methods,

And the following variations of methods,

For these methods,

  • changeNameByString changes the value of a String that is passed to it
  • changeNameUsingMethod calls a method within the class to change the name
  • changeNameUsingAttribute changes the attribute itself, which I've naughtily left public (hey, it's an educational test, it's allowed for curiosity)
  • getNewDog assigns a newly declared dogClass to the object passed
  • returnNewDog returns a newly declared dogClass

Here's my test ...

And here's the result ...

So basically, if you pass an object to a method, and manipulate it, the changes will happen to the original [changeNameUsingMethod  & changeNameUsingAttribute ]

If you use the method to create a new object [getNewDog], that object will be lost, unless you return it, and assign the new object to the old one [returnNewDog].

If you pass an attribute for the method, then change it, those changes are lost when you leave the method - basically a copy is made [changeNameByString].

This was a really fun piece of learning for all of us.  It also highlights my testing approach to development - which is "find a way to test and check what happens - come up with variations, and see what happens".  Don't be so sure that something can't possibly happen - find evidence to prove or disprove.

If you're shocked with the result, then you've found an area to learn more about.  Target some study there.

And most of all, have fun!

Find this example here in Github.

No comments:

Post a Comment