Objects as parameters value vs reference semantics reading

Objects as parameters: value vs. reference semantics reading: 3. 3 cont’d 1

Value semantics • value semantics: Behavior where variables are copied when assigned to each other or passed as parameters. – Primitive types in Java use value semantics. – When the value of one variable is assigned to another, the value is copied into the other variables unique space. – Modifying the value of one variable does not affect others. • Example: int y = x = 2 x = 5; y = x; 17; 8; x 5 8 y // x = 5, y = 5 // x = 5, y = 17 // x = 8, y = 17 17 5

Swapping primitive values • Consider the following code to swap two int variables: public static void main(String[] args) { int a = 7; int b = 35; System. out. println(a + " " + b); // swap a with b a = b; b = a; System. out. println(a + " " + b); } – What is wrong with this code? What is its output? • Correct code to swap two int variables: int temp = a; a = b; b = temp; Need a temporary variable. Two car garage analogy. 3 Output: 35 35

A swap method? • Swapping is a common operation, so we might want to make it into a method. – Does the following swap method work? Why or why not? 4 public static void main(String[] args) { int a = 7; int b = 35; System. out. println(a + " " + b); // swap a with b swap(a, b); System. out. println(a + " " + b); } public static void swap(int a, int b) { int temp = a; a = b; b = temp; Output: 7 35 }

int a = 7; int b = 35; 7 35 main. a main. b // swap a with b swap(a, b); 7 35 swap. a swap. b public static void swap(int a, int b) { int temp = a; a = b; b = temp; } 5

int a = 7; int b = 35; 7 35 main. a main. b // swap a with b swap(a, b); 7 35 swap. a swap. b 7 temp public static void swap(int a, int b) { int temp = a; a = b; b = temp; } 6

int a = 7; int b = 35; 7 35 main. a main. b // swap a with b swap(a, b); 35 35 swap. a swap. b 7 temp public static void swap(int a, int b) { int temp = a; a = b; b = temp; } 7

int a = 7; int b = 35; 7 35 main. a main. b // swap a with b swap(a, b); Even though the variables in main() and swap() have the same names, they are not in each other’s scope. Thus, they are different variables and have different memory locations. 35 swap. a swap. b 7 7 temp public static void swap(int a, int b) { int temp = a; Now the values a and b values in a = b; swap() are interchanged. Note that this b = temp; has no affect on a and b in main(). } 8

int a = 7; int b = 35; 7 35 main. a main. b // swap a with b swap(a, b); Even though the variables in main() and swap() have the same names, they are not in each other’s scope. Thus, they are different variables and have different memory locations. 35 swap. a swap. b 7 7 temp public static void swap(int a, int b) { int temp = a; Now the values a and b values in a = b; swap() are interchanged. Note that this b = temp; has no affect on a and b in main(). } 9

Modifying primitive parameters • When we call a method and pass primitive variables' values as parameters, we can assign new values to the parameters inside the method. – But this does not affect the value of the variable that was passed; its value was copied, and the two variables are otherwise distinct. – Example: public static void main(String[] args) { int x = 1; foo(x); x 1 System. out. println(x); // output: 1 } public static void foo(int x) { value 1 is copied into parameter x = 2; } x 10 1 2 parameter's value is changed to 2 (variable x in main is unaffected)

• Value semantics With primitive types, the value of the variable is on the right of an = is copied and stored in the place given by the variable on the left of the equal sign. int x = 8; // x 8 int y = x; // y 11

• Value semantics With primitive types, the value of the variable is on the right of an = is copied and stored in the place given by the variable on the left of the equal sign. int x = 8; // x 8 8 int y = x; // y 12

• Value semantics With primitive types, the value of the variable is on the right of an = is copied and stored in the place given by the variable on the left of the equal sign. int x = 8; // x 8 8 int y = x; // y 13

• Value semantics With primitive types, the value of the variable is on the right of an = is copied and stored in the place given by the variable on the left of the equal sign. int x = 8; // x 8 int y = x; // y 8 14

IGNORE: Reference semantics and Strings With objects, the place in memory named by that object does not contain the object’s value but a reference (memory address) of the place that actually stores the object. String greedy = “This is mine. ”; // greedy This is mine. • Efficiency and sharing It is frequently adequate (or even preferred) to share an object rather than having multiple copies of it. References allow this. String share = greedy; // share = “You can have it. ”; The reference value in greedy is copied into share, notice thicker arrow. share now is a reference to the same String as greedy. Share now points to the same string as greedy does. But changing one does not change the other due to immutability. You can have it. 15

When you copy a primitive type, it copies the value. When you copy an object, it copies the reference. The contents of the place in memory Memory are always copied. In one case it is a value and in the other is a reference. int a Point b Point a pt 1 b pt 2 = 7; pt 1 = new Point(9, 20); = a; pt 2 = pt 1; pt 1 and pt 2 point to the same object. The following two statements do exactly the same thing, { Point pt 1. translate(5, 7) OR pt 2. translate(5, 7) Both end up with the object having the values x = 14, y = 27. 7 7 14 9 27 20 16

The same thing happens when you pass parameters to a method. When you pass a primitive type, it copies the value. When you pass an object, it copies the reference. int a = 7; Point pt 1 = new Point(9, 20); moo(a, pt 1); . . . Memory a pt 1 { Point 7 9 20 17

The same thing happens when you pass parameters to a method. When you pass a primitive type, it copies the value. When you pass an object, it copies the reference. int a = 7; Point pt 1 = new Point(9, 20); moo(a, pt 1); . . . public static int moo(int b, Point pt 2) { pt 2. x = 14; pt 2. y = 27 Memory a pt 1 7 b pt 2 7 { Point 9 20 18

The same thing happens when you pass parameters to a method. When you pass a primitive type, it copies the value. When you pass an object, it copies the reference. int a = 7; Point pt 1 = new Point(9, 20); moo(a, pt 1); . . . public static int moo(int b, Point pt 2) { pt 2. x = 14; pt 2. y = 27 Memory a pt 1 7 b pt 2 7 { Point 14 20 19

The same thing happens when you pass parameters to a method. When you pass a primitive type, it copies the value. When you pass an object, it copies the reference. int a = 7; Point pt 1 = new Point(9, 20); moo(a, pt 1); . . . public static int moo(int b, Point pt 2) { pt 2. x = 14; pt 2. y = 27 Memory a pt 1 7 b pt 2 7 { Point But Points are mutable so changing the value in the method moo() changes the value in main(). 14 27 20

Reference semantics • reference semantics: Behavior where variables refer to a common value when assigned to each other or passed as parameters. – Objects in Java use reference semantics. – Object variables do not actually store an object; they store the address of an object's location in the computer memory. • Variables for objects are called reference variables. • We often draw reference variables as small boxes that point an arrow toward the object they refer to. – Example: Point p 1 = new Point(3, 8); p 1 21 x 3 y 8

Multiple references • If two reference variables are assigned to refer to the same object, the object is not copied. – Both variables literally share the same object. – Calling a method on either variable will modify the same object. Point p 1 = new Point(3, 8); Point p 2 = new Point(2, -4); Point p 3 = p 2; p 1 x 3 y 8 p 2 x 2 y -4 p 3 Here 3 variables refer to 2 objects. If we change p 3, will p 2 change? If we change p 2, will p 3 change? E. g. p 3. x = 15; p 2. y = 25 22

Multiple references • If two reference variables are assigned to refer to the same object, the object is not copied. – Both variables literally share the same object. – Calling a method on either variable will modify the same object. Point p 1 = new Point(3, 8); Point p 2 = new Point(2, -4); Point p 3 = p 2; p 1 x 3 y 8 p 2 x 15 y 25 p 3 Here 3 variables refer to 2 objects. If we change p 3, will p 2 change? If we change p 2, will p 3 change? E. g. p 3. x = 15; p 2. y = 25 Yes to both. 23

Multiple references • If two variables refer to the same object, modifying one of them will also make a change in the other: p 3. translate(5, 1); System. out. println("(" + p 2. x + " " + p 2. y + ")"); p 1 x 3 y 8 p 2 x 2 7 y -4 -3 p 3 OUTPUT: (7, -3) 24

Multiple references • If two variables refer to the same object, modifying one of them will also make a change in the other: p 3. translate(5, 1); System. out. println("(" + p 2. x + " " + p 2. y + ")"); p 1 p 2 p 3 x x 3 15 20 y 8 y 26 25 OUTPUT: (20, 26) There is no need to write p 3 = p 3. translate(5, 1). Whereas if we have String str = “Hi there”; // We must have str = str. substring(0, 2); // because the following does not change str. substring(0, 2); // Why? 25 Humans, who designed Java, are inconsistent Also due to String immutability, but that is a longer story.

Why references? • The fact that objects are passed by reference was done for several reasons: 26 – efficiency. Objects can be large, bulky things. Having to copy them every time they are passed as parameters would slow down the program. – sharing. Since objects hold important state and have behavior that modifies that state, it is often more desirable for them to be shared by parts of the program when they're passed as parameters. Often we want the changes to occur to the same object. – But, it is often considered a bad idea to change object parameters within a method. It is better to return a new object of the type that you want. The translate method in Point does not conform to this rule. It actually changes the invoking object.

Objects as parameters • When an object is passed as a parameter, the object is not copied. The same object is shared by the original variable and parameter. – If a method is called on the parameter, it will affect the original object that was passed to the method. – Since the variable p 1 and the parameter p refer to the same object, modifying one will also make a change in the other: public static void main(String[] args) { Point p 1 = new Point(2, 3); example(p 1); } public static void example(Point p) { p. set. Location(-1, -2); } p 1 x 2 -1 y 3 -2 p 27
![Activity: What does this code print? public static void main(String[] args) { int a Activity: What does this code print? public static void main(String[] args) { int a](http://slidetodoc.com/presentation_image_h2/6e73ba098ac26a49bbbe47964d18815d/image-28.jpg)
Activity: What does this code print? public static void main(String[] args) { int a = 7; Point pt 1 = new Point(10, 15); Point pt 2 = new Point(30, 40); pt 2 = mystery(a, pt 1); System. out. println("a= " + a); System. out. println(pt 1); System. out. println(pt 2); } public static Point mystery(int c, Point pt 3) // Now c = 10 { c += 3; pt 3. translate(c, c); Now pt 3 and pt 1 contain x = 20, y = 25 Point pt 4 = new Point(pt 3. y, pt 3. x); return pt 4; } Now pt 4 is x = 25, y = 20 a= 7 java. awt. Point[x=20, y=25] java. awt. Point[x=25, y=20] 28

Modifying Strings • The methods that appear to modify a string (substring, to. Lower. Case, to. Upper. Case, etc. ) actually create and return a new string. String s = "lil bow wow"; s. to. Upper. Case(); System. out. println(s); // output: lil bow wow • If you want to modify the variable, you must reassign it to store the result of the method call: String s = "lil bow wow"; s = s. to. Upper. Case(); System. out. println(s); // output: LIL BOW WOW 29

The String type is called immutable because Strings can not be modified! (This occasionally becomes a problem with strings as method parameters. Otherwise, it can be ignored. ) The methods that appear to modify a string: substring, to. Lower. Case, to. Upper. Case, . . . actually create and return a new string. String s = "I am immutable"; s. to. Upper. Case(); System. out. println(s); // output: I am immutable If you want to modify the variable, you must reassign it to store the result of the method call: String s = "I am immutable"; s = s. to. Upper. Case(); System. out. println(s); // output: I AM IMMUTABLE This is like the fact that i + 1; does not change i, you must say i = i + 1; (or the shorthand i++; ) to store the changed value back into i. 30

General review 31

/* Returns the integer sum of the values from small to big. */ public static int. Sum(int small, int big) { int sum = 0; for ( int i = small; i <= big ; i++) sum = sum + i; return sum; } /* Returns the integer sum of the values from 1 to value */ public static int. Sum(int value){ int sum = 0. 0; for ( int i = 1; i <= value; i++) { sum = sum + i; } return sum; } } 32

Math. random() returns a random double value in the range [0. 0, 1. 0). In English this says it returns a random value in the range from 0. 0 (including 0. 0, or inclusive) and 1. 0 (not including 1. 0, or exclusive). Thus, the range is 0. 0 through 0. 99999…. (This is needed in Assignment 4. ) Often we want a value that is an integer in a certain range. Say want a value in the range [1, 10]. Would the following return a value of 1 to 10, inclusive? (int) (Math. random() * 10); // no, returns a value in the range 0 to 9 Why? Math. random() returns a value in the range 0. 0 through 9. 9999, (int)(0. 0 * 10) = 0, (int) (0. 999999 * 10) = (int)(9. 99999) = 9 What can we do? Add 1. int One. To 10 = (int) (Math. random() * 10) + 1; // One. To 10 has a value in // the range [1, 10]. (int) (0. 0 + 1. 0) = 1 (int) (9. 99999 + 1. 0) = 10 33

Assume we have a string of 4 characters, e. g. String my. String = “cave”; c a v e 0 1 2 3 We can generate a String with those letters in reverse by using Can’t concatenate 2 characters, must make them string concatenations using the empty string. Often strings are initialized to the empty string before a loop much as integers are initialized to 0. String rev. String = "" + my. String. char. At(3) + my. String. char. At(2) + my. String. char. At(1) + my. String. char. At(0); The above assignment yields the following characters from each of the my. String. char. At() method calls. rev. String = "" + ‘e’ + ‘v’ + ‘a’ + ‘c’; e v a c 0 1 2 3 When working with Strings, initializing to “” (the empty string) is as common as initializing an int to 0 or 1. 34
![public class Get. Chars { public static void main(String[] args) { String this. Bunch. public class Get. Chars { public static void main(String[] args) { String this. Bunch.](http://slidetodoc.com/presentation_image_h2/6e73ba098ac26a49bbbe47964d18815d/image-35.jpg)
public class Get. Chars { public static void main(String[] args) { String this. Bunch. Of. Characters = "this Bunch Of Characters"; print. Reverse. Chars(this. Bunch. Of. Characters); } } public static void print. Reverse. Chars(String str) { for ( int i = str. length() - 1; i >= 0; i-- ) System. out. println("Character " + i + " is " +"'" + str. char. At(i) + "'. "); } Character 23 is 's'. Character 22 is 'r'. Character 21 is 'e'. Character 20 is 't'. Character 19 is 'c'. Character 18 is 'a'. Character 17 is 'r'. Character 16 is 'a'. Character 15 is 'h'. Character 14 is 'C'. Character 13 is ' '. Character 12 is 'f'. Character 11 is 'O'. Character 10 is ' '. Character 9 is 'h'. Character 8 is 'c'. Character 7 is 'n'. Character 6 is 'u'. Character 5 is 'B'. Character 4 is ' '. Character 3 is 's'. Character 2 is 'i'. Character 1 is 'h'. Character 0 is 't'. 35

This and the next 4 slides are very skippable The String type is called immutable because Strings can not be modified! When a String takes on a new value, a brand new string is formed, the pointer to the new string is copied into the string pointer so it points to the newly created string. Copying the new string pointer into the variable destroys the old string pointer. String greedy = "This is mine. "; String share = greedy; System. out. println(share); share = "You can have it. "; System. out. println(share); System. out. println(greedy); Output: This is mine. You can have it. This is mine. 36
![public class Immutable { public static void main(String[] args) { String str 1 = public class Immutable { public static void main(String[] args) { String str 1 =](http://slidetodoc.com/presentation_image_h2/6e73ba098ac26a49bbbe47964d18815d/image-37.jpg)
public class Immutable { public static void main(String[] args) { String str 1 = "I am immutable. "; String str 2 = str 1; System. out. println("str 1 = " + str 1 + " str 2 = "What does that mean? "; System. out. println("str 1 = " + str 1 + " my. Method(str 1); System. out. println("str 1 = " + str 1); } Output: str 1 = I am immutable. str 2 = I am immutable. str 1 = I am immutable. str 2 = What does that mean? method. Str = It's complicated. str 1 = I am immutable. temp. String = Immutable I am. str 2 = " + str 2); Skip this slide? str 2 = " + str 2); str 1 I am immutable. str 1 = my. Other. Method(str 1); public static void my. Method(String method. Str) { method. Str = "It's complicated. "; System. out. println("method. Str = " + method. Str); } It’s complicated. method. Str Note: substring is overloaded. It can have either 1 or 2 parameters. 1 parameter means to extract from that position to the end of the string. public static String my. Other. Method(String other. Str) { String temp. String = other. Str. substring(5, 6). to. Upper. Case() + other. Str. substring(6, 14); temp. String = temp. String + " " + other. Str. substring(0, 4) + other. Str. substring(14); System. out. println("temp. String = " + temp. String); return temp. String; }} 37

Reference semantics for Strings does not work like those for other objects due to String immutability. Skip this slide? With objects, the place in memory named by that object does not contain the object’s value but a reference (memory address) of the place that actually stores the object. String greedy = “This is mine. ”; // greedy This is mine. • Efficiency and sharing It is frequently adequate (or even preferred) to share an object rather than having multiple copies of it. References allow this. The reference value in greedy String share = greedy; // share = “You can have it. ”; is copied into share, notice thicker arrow. share now is a reference to the same String as greedy. Share now points to the same string as greedy does. But changing share to a new string, creates a new string and points share to it. The string that share used to point to is not modified by the assignment, because the string is immutable. So the string in greedy stays the same. You can have it. 38
![public class Immutable { public static void main(String[] args) { String str 1 = public class Immutable { public static void main(String[] args) { String str 1 =](http://slidetodoc.com/presentation_image_h2/6e73ba098ac26a49bbbe47964d18815d/image-39.jpg)
public class Immutable { public static void main(String[] args) { String str 1 = "I am immutable. "; String str 2 = str 1; Skip this slide? System. out. println("str 1 = " + str 1 + " str 2 = "What does that mean? "; System. out. println("str 1 = " + str 1 + " str 2 = " + str 2); my. Method(str 1); System. out. println("str 1 = " + str 1); str 1 str 2 = " + str 2); } public static void my. Method(String method. Str) { method. Str = "It's complicated. "; System. out. println("method. Str = " + method. Str); } I am immutable. It’s complicated. method. Str } Output: str 1 = I am immutable. str 2 = I am immutable. str 1 = I am immutable. str 2 = What does that mean? method. Str = It's complicated. str 1 = I am immutable. The variables str 1 and method. Str originally point to the same string (“I am immutable”). str 1 and method. Str are two different places in memory. String “It’s complicated” is generated and method. Str now points at it, no longer at “I am immutable”. 39
- Slides: 39