02 - 11/17/10 19:40:42 1 02 CS 61B: Lecture 2 Monday,...

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

View Full Document Right Arrow Icon
11/17/10 19:40:42 1 02 CS 61B: Lecture 2 Monday, August 30, 2010 Homework 1 is available and due this Friday! Today’s reading: Sierra & Bates, Chapter 2; pp. 54-58, 154-160, 661, 669. OBJECTS AND CONSTRUCTORS ======================== String s1; // Step 1: declare a String variable. s1 = new String(); // Step 2: assign it a value: a new empty string. At this point, s1 and s2 are both --- ------ --- ------ variables that reference empty strings. s1 |.+---->| | s2 |.+---->| | --- ------ --- ------ s1 = "Yow!"; // Construct a new String; make s1 a reference to it. --- ---------- s1 |.+---->| Yow! | --- ---------- s2 = s1; // Assign s2 the value of s1. --- ---------- --- s1 |.+---->| Yow! |<----+.| s2 --- ---------- --- Now s1 and s2 reference the same object. What if we’d prefer to have a copy of the object? s2 = new String(s1); // Construct a copy of s1; make s2 a reference to it. --- ---------- --- ---------- s1 |.+---->| Yow! | s2 |.+---->| Yow! | --- ---------- --- ---------- Now they refer to two different, but identical, objects. Think about that. When Java executes that line, it does the following things, in the following order. - Java looks inside the variable s1 to see where it’s pointing. - Java follows the pointer to the String object. - Java reads the characters stored in that String object. - Java creates a new String object that stores a copy of those characters. - Java makes s2 reference the new String object. We’ve seen three String constructors: (1) new String() constructs an _empty_string_--it’s a string, but it contains no characters. (2) "cs 4" constructs a string containing the characters cs 4. (3) new String(s1) takes a _parameter_ s1. Then it makes a copy of the object that s1 references. Constructors _always_ have the same name as their class, except the special
Background image of page 1

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

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 01/10/2012 for the course CS 61B taught by Professor Canny during the Fall '01 term at University of California, Berkeley.

Page1 / 2

02 - 11/17/10 19:40:42 1 02 CS 61B: Lecture 2 Monday,...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online