{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

05-linked_nodes - CSE 143 Lecture 5 References and Linked...

Info iconThis preview shows pages 1–5. Sign up to view the full content.

View Full Document Right Arrow Icon
1 CSE 143 Lecture 5 References and Linked Nodes slides created by Marty Stepp and Ethan Apter http://www.cs.washington.edu/143/ 2 Values vs. References • Does the following swap method work? Why or why not? public static void main(String[] args) { int a = 7; int b = 35; // 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; }
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
2 3 Value semantics value semantics : Behavior where values are copied when assigned to each other or passed as parameters. When one primitive is assigned to another, its value is copied. Modifying the value of one variable does not affect others. int x = 5; int y = x ; // x = 5, y = 5 y = 17; // x = 5, y = 17 x = 8; // x = 8, y = 17 4 Reference semantics reference semantics : Behavior where variables actually store the address of an object in memory. When one reference variable is assigned to another, the object is not copied; both variables refer to the same object . int[] a1 = {4, 5, 2, 12, 14, 14, 9}; int[] a2 = a1 ; // refers to same array as a1 a2[0] = 7; System.out.println( a1[0] ); // 7 index 0 1 2 3 4 5 6 value 5 2 12 14 14 9 7 a1 a2
Background image of page 2
3 5 References and objects • In Java, objects and arrays use reference semantics. Why? efficiency. Copying large objects slows down a program. sharing. It's useful to share an object's data among methods. DrawingPanel panel1 = new DrawingPanel(80, 50); DrawingPanel panel2 = panel1; // same window panel2.setBackground(Color.CYAN); panel1 panel2 6 Null references null : A value that does not refer to any object. The elements of an array of objects are initialized to null . String[] words = new String[5]; not the same as the empty string "" or the string "null" index 0 1 2 3 4 value null null null null null words
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
4 7 Null references Uninitialized reference fields of an object are initialized to null . public class Student { String name; int id; } Student timmy = new Student(); name null timmy id 0 8 Things you can do w/ null • store null in a variable or an array element String s = null; words[2] = null; • print a null reference System.out.println(timmy.name); // null
Background image of page 4
Image of page 5
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}