
Materials for Quiz 3
1. Creating objects
•Creating object reference variable
A class name can be used as a type to declare an object reference variable
String title;
// String is a class name
// title is declared as String reference variable
•Creating object
Generally, we use the new operator to create an object
title = new String (“Java Programming”);
// String (“Java Programming”) is String constructor, which is
// a special method that sets up the object
// To create a String object, there is another way to do it:
// title = “Java Programming”;
•Invoking methods
use the dot operator to invoke its methods
count = title.length();
//length() is method of String object, title
•References
An object reference can be thought of as a pointer to the location of the object
String name1 = “Tom”;
String name2 = “Mike”;
System.out.println(“name1: ” + name1 + “ name2: ” + name2);
//name1: Tom name2: Mike
name2 = name1;
// name2 points to the object which name1 points to
System.out.println(“name1: ” + name1 + “ name2: ” + name2);
//name1: Tom name2: Tom
// String object “Mike” has no object reference
// variable pointing to it and is ready to be
// garbage collected by java compiler automatically
name1 = “Peter”;
System.out.println(“name1: ” + name1 + “ name2: ” + name2);
//name1: Peter name2: Tom
2. String Class
•Two ways to create String object
//with new
String title = new String (“Java Programming”);
or
//without new
String title = “Java Programming”;