Slide 1

Slide 1 text

CSE110 Principles of Programming with Java Lecture 25: References as Parameters Javier Gonzalez-Sanchez [email protected] javiergs.engineering.asu.edu | javiergs.com Office Hours: By appointment

Slide 2

Slide 2 text

Objects as Parameters

Slide 3

Slide 3 text

Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 3 Objects as Parameters • Parameters in a Java method are passed by value • This means that a copy of the actual parameter (the value passed in) is stored into the formal parameter (in the method header) • Passing parameters is therefore similar to an assignment statement • When an object is passed as a parameter to a method, the actual parameter and the formal parameter become aliases of each other

Slide 4

Slide 4 text

Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 4 Object as Parameters

Slide 5

Slide 5 text

Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 5 Objects as Parameters • Since a1 is a primitive data, any change that was made to f1 in the method changeValues does not affects a1 • The object a2 was assigned to the value “222” and when a2 was passed to changeValues method, a2 and f2 became aliases so the change made to f2 will be seen in a2 in the main method. • The object a3 was assigned to the value “333” and when a3 was passed to changeValues method, a3 and f3 became aliases. However when f3 was re-instantiated with the reserved word new, f3 is given a different address from the one a3 has, thus any change made to f3 after that point will not affect a3 in the main method.

Slide 6

Slide 6 text

Arrays as Parameters

Slide 7

Slide 7 text

Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 7 Arrays as Parameters • An entire array can be passed as a parameter to a method • Object and arrays are passed as a reference, making the formal and actual parameters aliases of each other • Therefore, changing an array element within the method changes the original • An individual array element can be passed to a method as well, in which case the type of the formal parameter is the same as the element type

Slide 8

Slide 8 text

Javier Gonzalez-Sanchez | CSE110 | Summer 2017 | 8 Example

Slide 9

Slide 9 text

Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 9 Arrays of Objects

Slide 10

Slide 10 text

Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 10 Arrays of Objects

Slide 11

Slide 11 text

Javier Gonzalez-Sanchez | CSE110 | Summer 2017 | 11 Reference Chapter 6

Slide 12

Slide 12 text

CSE110 - Principles of Programming Javier Gonzalez-Sanchez [email protected] Summer 2020 Disclaimer. These slides can only be used as study material for the class CSE110 at ASU. They cannot be distributed or used for another purpose.