Values vs. References Lecture 13.

Slides:



Advertisements
Similar presentations
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
Advertisements

Topic 10 Java Memory Management. 1-2 Memory Allocation in Java When a program is being executed, separate areas of memory are allocated for each class.
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Stacks CS-240 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed in reverse.
Pointers “Absolute C++” Section 10.1
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
Arrays (Part 1) Computer Science Erwin High School Fall 2014.
Java Methods. Topics  Declaring fields vs. local variables  Primitive data types  Strings  Compound Assignment  Conversions from one value to another.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Problem Solving using the Java Programming Language May 2010 Mok Heng Ngee Day 5: Arrays.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Problem of the Day  Why are manhole covers round?
Problem of the Day  Why are manhole covers round?
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
Variables, Primitives, and Objects A Visual Learner’s Guide.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Classes and Objects CS177 Rec 10. Announcements Project 4 is posted ◦ Milestone due on Nov. 12. ◦ Final submission due on Nov. 19. Exam 2 on Nov. 4 ◦
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Objects and Classes.
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
Java 5 Class Anatomy. User Defined Classes To this point we’ve been using classes that have been defined in the Java standard class library. Creating.
Functions, Scope & File IO C++ Lecture 4 Bhaskar Bhattacharya.
IndexedListWithIteratorsViaLinear1Ind
Debugging with Eclipse
Chapter 4 Stacks
Java Memory Management
Stacks II David Lillis School of Computer Science and Informatics
Exceptions David Rabinowitz.
GC211 Data Structure Lecture 1 Sara Alhajjam.
Java Memory Management
Class Structure 15-Jun-18.
Dr. Bernard Chen Ph.D. University of Central Arkansas
Week 3 - Friday CS221.
Edvin von Otter & Todd Barker
Stack Data Structure, Reverse Polish Notation, Homework 7
CS Week 14 Jim Williams, PhD.
Arrays Part 1 Topic 19 - Stan Kelly-Bootle
Prof. Neary Adapted from slides by Dr. Katherine Gibson
CS 200 Arrays, Loops and Methods
CSC 253 Lecture 8.
Class Structure 16-Nov-18.
Phil Tayco Slide version 1.0 Created Oct 16, 2017
CSC 253 Lecture 8.
Organizing Memory in Java
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
int [] scores = new int [10];
Class Structure 7-Dec-18.
Defining methods and more arrays
Class Structure 2-Jan-19.
CS 200 Loops Jim Williams, PhD.
CS 200 Primitives and Expressions
CISC/CMPE320 - Prof. McLeod
Building Java Programs
Class Structure 25-Feb-19.
Arrays an array of 5 ints is filled with 3,2,4,1,7
Arrays in Java.
Stacks CS-240 Dick Steflik.
Suggested self-checks: Section 7.11 #1-11
Data Structures & Algorithms
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
LCC 6310 Computation as an Expressive Medium
Loops CGS3416 Spring 2019 Lecture 7.
Instructor: Dr. Michael Geiger Spring 2019 Lecture 23: Exam 2 Preview
Review for Midterm 3.
Classes and Objects Object Creation
Corresponds with Chapter 5
SPL – PS2 C++ Memory Handling.
Week 7 - Monday CS 121.
Presentation transcript:

Values vs. References Lecture 13

Office Hours Feedback After an appointment ends you'll be asked to complete a 3 question feedback form. The team does not see feedback immediately and any feedback shared with team members will be anonymized like course evals Were we welcoming and respectful? Did we genuinely try to help you learn the concepts? Overall, were we excellent? There's an optional field for notes, too. If a TA does a great job, let us know! Honest feedback here is critical for helping us improve!

Office Hours Feedback After an appointment ends The TAs are asked to complete a 3 question feedback form, too. This is to help us reach out to students who need extra help and ensure office hours is being used effectively Did the student come prepared and with a demonstrated effort? Was the student respectful and engaged in learning? Overall, do you have any concerns about the student's progress in 110?

What's on the horizon... PS3 Part 2 – Due Friday at 11:59pm WS4 – Out today due Sunday at 11:59pm MT1 – Next Thursday PS4 – Emoji - Will be released this week and due after Spring Break. A simple emoji that earns full credit should take ~2-4 hours Intricate emoji for fun – as long as you'd like!

Warm-up Question #1: What is the output? int x = 1; int y = x; x = 2; System.out.println(x); System.out.println(y);

Warm-up Question #2: What is the output? Egg a = new Egg(); Egg b = a; a.boil(); console.print(a.isRaw()); console.print(b.isRaw()); public class Egg { private boolean _raw; public Egg() { _raw = true; } public void boil() { _raw = false; public boolean isRaw() { return _raw; } }

Variables that hold simple types Actually store their values! When you declare a variable of type int, double, boolean, char you are reserving space in memory to hold a single value of that type When you assign to a variable, the value is copied into the variable's space in memory Let's look at an example

Code Memory Stack Heap File: Demo0.java int x = 1; int y = x; x = 2; public static void main(String[] args) { int x = 1; int y = x; x = 2; System.out.println(x); System.out.println(y); } File: Demo0.java

Code Memory Stack Heap x File: Demo0.java int x = 1; int y = x; 1 public static void main(String[] args) { int x = 1; int y = x; x = 2; System.out.println(x); System.out.println(y); } File: Demo0.java 1 x int

Code Memory Stack Heap x y File: Demo0.java int x = 1; int y = x; 1 public static void main(String[] args) { int x = 1; int y = x; x = 2; System.out.println(x); System.out.println(y); } File: Demo0.java 1 x int 1 y int

Code Memory Stack Heap x y File: Demo0.java int x = 1; int y = x; 20 public static void main(String[] args) { int x = 1; int y = x; x = 20; System.out.println(x); System.out.println(y); } File: Demo0.java 20 x int 1 y int

Variables that "hold" arrays and objects... A variable cannot actually store arrays or objects A variable can only store a reference to an array or an object When you assign to such a variable, you are copying the reference Thus, different variables can refer to the same thing "Roy", "Roy Williams", "Coach Williams", "Coach", "me", "I"

Code Memory Stack Heap File: Demo1.java Egg a = new Egg(); Egg b = a; public static void main(String[] args) { Egg a = new Egg(); Egg b = a; Egg c = new Egg(); a.boil(); // ... } File: Demo1.java

Code Memory Stack Heap _raw Step 1. When the new keyword is encountered, space is reserved on the Heap to store every field of an object or every element of an array. public static void main(String[] args) { Egg a = new Egg(); Egg b = a; Egg c = new Egg(); a.boil(); // ... } File: Demo1.java Egg _raw boolean

Then, for object types, the constructor is called. Code Memory Stack Heap Step 2. Then, for object types, the constructor is called. public static void main(String[] args) { Egg a = new Egg(); Egg b = a; Egg c = new Egg(); a.boil(); // ... } File: Demo1.java Egg _raw boolean

Code Memory Stack Heap this _raw Step 3. Java sets up a new Stack frame and automatically sets up a this variable that points to the object. Stack Heap public Egg() { _raw = true; } File: Egg.java this Egg public static void main(String[] args) { Egg a = new Egg(); Egg b = a; Egg c = new Egg(); a.boil(); // ... } File: Demo1.java Egg _raw boolean

All field references refer to the fields of the this object. Code Memory All field references refer to the fields of the this object. Stack Heap public Egg() { _raw = true; } File: Egg.java this Egg public static void main(String[] args) { Egg a = new Egg(); Egg b = a; Egg c = new Egg(); a.boil(); // ... } File: Demo1.java Egg true _raw boolean

Code Memory Stack Heap this a _raw When the end of the constructor is reached, a reference to the constructed object is returned. Stack Heap public Egg() { _raw = true; } File: Egg.java this Egg public static void main(String[] args) { Egg a = new Egg(); Egg b = a; Egg c = new Egg(); a.boil(); // ... } File: Demo1.java a Egg Egg true _raw boolean

Code Memory Stack Heap a _raw Finally, the code jumps back to the main method and the constructor's stack frame is erased. public static void main(String[] args) { Egg a = new Egg(); Egg b = a; Egg c = new Egg(); a.boil(); // ... } File: Demo1.java a Egg Egg true _raw boolean

Code Memory Stack Heap a _raw b Notice we are not constructing a new Egg, we are taking a's value, which is a reference to an egg, and assigning it to b. public static void main(String[] args) { Egg a = new Egg(); Egg b = a; Egg c = new Egg(); a.boil(); // ... } File: Demo1.java a Egg Egg true _raw boolean b Egg

Code Memory Stack Heap c _raw a _raw b All of the same steps we moved through to construct a, we would also do for c... Egg true _raw boolean c Egg public static void main(String[] args) { Egg a = new Egg(); Egg b = a; Egg c = new Egg(); a.boil(); // ... } File: Demo1.java a Egg Egg true _raw boolean b Egg

Notice we now have two Egg objects in the Heap. Code Memory Stack Heap Notice we now have two Egg objects in the Heap. Egg true _raw boolean c Egg public static void main(String[] args) { Egg a = new Egg(); Egg b = a; Egg c = new Egg(); a.boil(); // ... } File: Demo1.java a Egg Egg true _raw boolean b Egg

Then we reach a method call. Code Memory Stack Heap Then we reach a method call. "Egg a, boil!" Egg true _raw boolean c Egg public static void main(String[] args) { Egg a = new Egg(); Egg b = a; Egg c = new Egg(); a.boil(); // ... } File: Demo1.java a Egg Egg true _raw boolean b Egg

Code Memory Stack Heap this c _raw a _raw b Java sets up a new Stack frame and automatically sets up a this variable that points to the object the method was called on. Code Memory Stack Heap public void boil() { _raw = false; } File: Egg.java this Egg Egg true _raw boolean c Egg public static void main(String[] args) { Egg a = new Egg(); Egg b = a; Egg c = new Egg(); a.boil(); // ... } File: Demo1.java a Egg Egg true _raw boolean b Egg

All field references refer to the fields of the this object. Code Memory Stack Heap public void boil() { _raw = false; } File: Egg.java this Egg Egg true _raw boolean c Egg public static void main(String[] args) { Egg a = new Egg(); Egg b = a; Egg c = new Egg(); a.boil(); // ... } File: Demo1.java a Egg Egg false _raw boolean b Egg

Code Memory Stack Heap this c _raw a _raw b End of a void method reached, nothing to return, so we'll just delete the stack frame and return back to our book mark. Code Memory Stack Heap public void boil() { _raw = false; } File: Egg.java this Egg Egg true _raw boolean c Egg public static void main(String[] args) { Egg a = new Egg(); Egg b = a; Egg c = new Egg(); a.boil(); // ... } File: Demo1.java a Egg Egg false _raw boolean b Egg

Code Memory Stack Heap c _raw a _raw b Notice the state of memory... two objects in the heap and three local variables in main's stack frame. Egg true _raw boolean c Egg public static void main(String[] args) { Egg a = new Egg(); Egg b = a; Egg c = new Egg(); a.boil(); // ... } File: Demo1.java a Egg Egg false _raw boolean b Egg

The "Stack" All local variables (and thus parameters!) are stored on the Stack Each method/constructor call has its own "frame" of the Stack Variables declared inside of either are stored in the frame When a method/constructor is called, a frame is pushed onto the top of the stack When a method/constructor completes, that frame is popped off the top of the stack

The "Heap" All objects and arrays are stored on the heap. Whenever your code encounters the new keyword, this is your clue that new space is being reserved on the Heap to hold an object or array. All variables on the stack which "hold" an object or an array hold references, also called pointers, to the actual values on the heap. When two variables refer to the same object or array, of course changes you make to one variable will impact the other.

Today: Egg Russian Roulette

Code Walk

Let's Run our Program Open EggRoulette.java Enter 2 Players We get a NullPointerException. What does that mean?

Follow-Along #1 – Let's Run our Program Open EggRoulette.java Under todo #1: _eggs = new Carton();

What happens when we construct a Carton? public Carton() { _eggs = new Egg[12]; } What is stored in each of _eggs' elements, though?

At this point notice all of the elements are empty Code Memory Stack Heap At this point notice all of the elements are empty public Carton() { _eggs = new Egg[12]; _eggs[0] = new Egg(); } File: Carton.java Carton _eggs: Egg[] this Carton … EggRoulette _carton Carton _carton = new Carton(); File: EggRoulette.java this EggRoulette

Let's imagine assigning index 0 a new Egg… Code Memory Stack Heap Let's imagine assigning index 0 a new Egg… public Carton() { _eggs = new Egg[12]; _eggs[0] = new Egg(); } File: Carton.java Carton _eggs: Egg[] this Carton … EggRoulette _carton Carton _carton = new Carton(); File: EggRoulette.java this EggRoulette

Code Memory Stack Heap _raw _eggs: this _carton this We've seen that the constructor of will return a reference to the new object on the Heap Egg true _raw boolean public Carton() { _eggs = new Egg[12]; _eggs[0] = new Egg(); } File: Carton.java Carton _eggs: Egg[] this Carton … EggRoulette _carton Carton _carton = new Carton(); File: EggRoulette.java this EggRoulette

This reference is assigned to the 0 index of the array… Code Memory Stack Heap This reference is assigned to the 0 index of the array… Egg true _raw boolean public Carton() { _eggs = new Egg[12]; _eggs[0] = new Egg(); } File: Carton.java Carton _eggs: Egg[] this Carton … EggRoulette _carton Carton _carton = new Carton(); File: EggRoulette.java this EggRoulette

Code Memory Stack Heap _raw _eggs: _carton this After the Carton construction is complete only one Egg element is initialized… how do we do the rest? Egg true _raw boolean Carton _eggs: Egg[] … EggRoulette _carton Carton _carton = new Carton(); File: EggRoulette.java this EggRoulette

Hands-on #1: Initialize all Eggs in the Carton Inside of Carton.java After constructing the _eggs array Write a for loop that constructs a new Egg for every element of the array… _eggs[ <index> ] = new Egg(); Check-in on PollEv.com/comp110 when complete

for (int i = 0; i < _eggs.length; i++) { _eggs[i] = new Egg(); }

What happens if we don't initialize our _carton or _eggs to new object references? Arrays that hold references to objects, as well as fields that hold references to objects… Are null by default. This means each element or field refers to nothing.

NullPointerException When you try to call a method on a null value, you will get a NullPointerException For example, before we initialized _carton, when our code reached: _carton.size() It caused a NullPointerException because _carton currently refers to nothing it is null. To avoid NullPointerExceptions always initialize array elements and fields!

How do we shuffle our Eggs in the Carton? We need to make use of our old friend… the swap We will also make use of a new class of object we've never seen before but is really handy for making Games… Introducing: java.util.Random The following code will print a random number between 0 and x, not inclusive of x: Random random = new Random(); int x = 12; int num = random.nextInt(x); System.out.println(num);

Hands-on #2: Randomize the Eggs in the Carton Inside of the shuffleEggs method's for loop find the todo Notice 2 indices of the carton are being chosen at Random Your job is to swap the Eggs at indices a and b To do so you will need a temp variable What type should this variable be? To remove and put back an Egg from the Carton, you will need to refer to Carton's takeEgg and setEgg methods Check-in on PollEverywhere when you think you have it

Egg temp = _carton.takeEgg(a); _carton.setEgg(a, _carton.takeEgg(b)); _carton.setEgg(b, temp);

How do we make it look like 2 rows of Eggs? The getShapes method of Carton is where our game's graphics are coming from… Let's see if we can be clever about how we position our X and Y of each egg…

double x = (i % 6) * (2 * shape.getRadius() + 10.0); double y = 0.0; if (i > 5) { y = 2 * (shape.getRadius() + 10); }

Let's play…