Upgrade to Pro — share decks privately, control downloads, hide ads and more …

CSE110 Lecture 25

CSE110 Lecture 25

Principles of Programming with Java
Arrays as Parameters
(202007)

B546a9b97d993392e4b22b74b99b91fe?s=128

Javier Gonzalez

June 26, 2017
Tweet

Transcript

  1. CSE110 Principles of Programming with Java Lecture 25: References as

    Parameters Javier Gonzalez-Sanchez javiergs@asu.edu javiergs.engineering.asu.edu | javiergs.com Office Hours: By appointment
  2. Objects as Parameters

  3. 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
  4. Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 4 Object

    as Parameters
  5. 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.
  6. Arrays as Parameters

  7. 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
  8. Javier Gonzalez-Sanchez | CSE110 | Summer 2017 | 8 Example

  9. Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 9 Arrays

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

    of Objects
  11. Javier Gonzalez-Sanchez | CSE110 | Summer 2017 | 11 Reference

    Chapter 6
  12. CSE110 - Principles of Programming Javier Gonzalez-Sanchez javiergs@asu.edu 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.