What We Will Cover
Illuminations
Questions on Completed Assignments?
- A4: Using Arrays (10/1/03)
- About how many comparisons are needed to sort an array of 100 elements using the unmodified bubble sort?
- About how many comparisons are needed to sort an array of 100 elements using the enhanced bubble sort?
- How much did our improvements to bubble sort improve its performance?
^ top
5.1: Java Strings
Objectives
At the end of the lesson the student will be able to:
- Use Strings in Java programs
- Convert Strings to primitive types
- Convert other types to Strings
- Parse Strings
|
^ top
5.1.1: About Strings
- Recall that a string is a sequence of characters
- String literals are made by enclosing a sequence of characters in double quotes
- For example:
"abc" "b" "3.14159" "$3.95" "My name is Ed"
Strings are stored as Unicode characters
String objects are used to store string data
String is a genuine class and has methods to operate on strings
String constant: one or more characters in double quotes
Examples:
char charVar = `A`; //single quotes
String stringVar = "A"; //double quotes
String line = "Hello, world!";
More information on Unicode: Unicode Home Page
Key Java Classes
- Key Java classes for string and character processing
Class java.lang.String
Class java.lang.StringBuffer
Class java.lang.Character
Class java.util.StringTokenizer
^ top
5.1.2: Creating Strings
- String assignments are different than for primitive types
- Actually a reference type because strings are objects in Java
- For instance:
String message;
message = new String("Please enter an identification code");
- First line declares a reference variable of type
String
- Second line creates a
String object in memory as assigns the object location to the reference variable

- Keyword
new is an operator that creates storage for an object
- Because this allocation occurs while the program is running, known as dynamic memory allocation
- Could combine the two steps into one line:
String message = new String("Please enter an ...");
String literals have a special syntax that does not require the new operator
String message = "Please enter an identification code";
Since this form is shorter, it is preferred by most Java programmers
String Constructors
- String class has nine (non-deprecated) constructors
- Constructors sometimes used to convert from byte or char arrays to strings
- More information: Class String from the Java API
^ top
5.1.3: String Methods
String Concatenation
- Most string operations are performed using methods rather than operators
- Because strings are really a Java class
- However, there is one string operator:
+
- Same sign as used for numerical addition
- For strings, performs a concatenation operation
- Joins two strings into one string
- For example:
"Java" + " rules!"
Concatenates the two strings into one string: "Java rules!"
Note that the + operator has the same precedence for strings and numbers
Can sometimes produce surprising results
For example:
System.out.println("The result is: " + 7 + 2);
Produces the output
The result is: 72
How can the programmer correct this problem?
^ top
5.1.4: String Conversions
- Often need to convert
String values to numeric types
- Java provides a very useful set of methods for converting between strings and primitive types
- These methods are known as wrapper classes
- Wrap a class structure around a primitive type

- Each conversion method is a
public and static
- General purpose methods that operate only on their arguments to produce a result
Strings to Primitive Values
Return Type |
Conversion Method |
Example |
int |
Integer.parseInt(String) |
Integer.parseInt("1234") |
long |
Long.parseLong(String) |
Long.parseLong("123456") |
float |
Float.parseFloat(String) |
Float.parseFloat("123.45") |
double |
Double.parseDouble(String) |
Double.parseDouble("123.45") |
Primitive Values to Strings
Type to Convert |
Conversion Method |
Example |
int |
Integer.toString(int) |
Integer.toString(1234) |
long |
Long.toString(long) |
Long.toString(123456) |
float |
Float.toString(float) |
Float.toString(123.45) |
double |
Double.toString(double) |
Double.toString(123.45) |
More Information
^ top
5.1.5: StringBuffer Class
- When a
String object is created, its contents cannot change
- Use a
StringBuffer to create and manipulate modifiable string data
- Like a
String object, a StringBuffer represents a sequence of characters
- However,
StringBuffer has mutator methods that can change its sequence of characters
- For example:
StringBuffer str = new StringBuffer("ABCDE");
str.reverse();
Sytem.out.println(str); // displays EDCBA
Note that StringBuffer does not return a new String object
Instead, it actually modifies the StringBuffer referred to by str
More information: Class StringBuffer from the Java API
^ top
5.1.6: Characters and the Character Class
- A character is a letter, number or special symbol
- For example:
'a' 'b' 'Z' '3' 'q' '$' '*'
Java provides the char data type to represent characters
Stores characters as a 16-bit unsigned value using Unicode
Large enough to store 65,536 distinct character codes
Unicode was designed to provide codes for all the world's alphabets
Internally, Java stores a char as an unsigned 16-bit number
- Range is from 0 to 65535
- Only Java type that is unsigned
Class Character used to treat primitive char variables as objects
One of several type-wrapper classes
Provides methods for determining a character's category, e.g. lowercase letter, digit
Also has methods for converting characters between uppercase and lowercase
More information: Class Character from the Java API
Escape Sequences
- Note that the first 32 character codes are not visible on our monitors
- Java can access some of the control codes using escape sequences
- Backslash (
\) directly in front of a select character tells the compiler to escape from the normal interpretation
- Following table has some nonprinting and hard-to-print characters:
| Escape |
Character Name |
Unicode Value |
|
Alert |
\u0007 |
\b |
Backspace |
\u0008 |
\f |
Formfeed |
\u000C |
\n |
Newline |
\u000A |
\r |
Carriage return |
\u000D |
\t |
Horizontal tab |
\u0009 |
\\ |
Backslash |
\u005C |
\" |
Double quote |
\u0022 |
\' |
Single quote |
\u0027 |
- Alert character causes the bell to ring
- To hear the bell, print the Unicode value
System.out.print('\u0007');
^ top
5.1.7: Parsing Strings
- Used to break a
String into tokens (substrings)
- Provide a set of delimiters
- For example:
import java.util.StringTokenizer;
class StrToken {
public static void main(String[] args) {
StringTokenizer st =
new StringTokenizer("Hi Mom, Welcome!", " ,!");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
^ top
Exercise 5.1
Take one minute to prepare an answer the following question:
- Write a method that returns
true is a String argument is a palindrome. A palindrome is a string that reads the same forwards and backwards. Ignore case in making the determination.
^ top
5.2: Coding Classes to Define Objects
Objectives
At the end of the lesson the student will be able to:
- Code instance variables, constructors, and instance methods of classes
|
^ top
5.2.1: About Classes and Objects
- In object-oriented programming, objects represent data values
- Called objects because often used to model objects in the real-world
- For example, a program modeling the solar system might have one planet object
- Each object would contain all the data about each planet
- We create a description of the object by writing a class
- A class describes the data values that make up an object
- With class
Planet, we might have values such as:
String name: name of the planet
double diameter: diameter of the planet
- A class not only describes the data values, but also how to manipulate the data
- For example, class Planet might have methods:
double getDiameter(): returns the diameter of the planet
void moveTo(x, y, z): adjust data values to model movement in space
- Data values of an object are called instance variables
- Similarly, operations on object data are performed by instance methods
- Instance variables are said to hold the state of an object
Encapsulation and Data Hiding
- Two important concepts of object-oriented programming:
Encapsulation: inclusion of a number of items into a single unit
Data hiding: restricting a user from seeing how data is actually stored in a class
- Publicly available attributes and operations are known as the interface
Benefits of Encapsulation and Data Hiding
- Allows a software engineer to concentrate on what an object is or does
- Implementation can be handled later or even by someone else
- Encourages code reuse and extensibility
- All interactions between objects use the interface
- Can change the implementation without changing the interface
- Can also add operations and attributes without changing the existing interface
- Improves maintainability
- If an interface is not changed, no other part of the application is affected
- Can change one class without changing other classes
^ top
5.2.2: Defining Classes
[accessModifier] class ClassName {
// Instance variable declaration section
variable declarations
// Constructor declaration section
variable declarations
// Instance method implementation section
method definitions
}
Contains three general sections:
- Variables
- Constructors
- Methods
public class Date {
// variable declaration section
private int month;
private int day;
private int year;
// constructor definition section
public Date() {
month = 12;
day = 25;
year = 2002;
}
public Date(int newMonth, int newDay, int newYear) {
month = newMonth;
day = newDay;
year = newYear;
}
// method definition section
public int getMonth() {
return month;
}
public int getDay() {
return day;
}
public int getYear() {
return year;
}
public void setDate(int mm, int dd, int yyyy) {
day = dd;
month = mm;
year = yyyy;
}
public void showDate() {
System.out.println(month + "/" + day
+ "/" + year % 100);
}
}
Access Modifiers and Data Hiding
- Note the keywords
private and public
- Referred to as access modifiers or visibility modifiers
private: can only be accessed by member methods of this class
public: can be accessed by member methods of any class
- Setting
private accessibility on all data members is a good design practice
- Enforces security by requiring access only through
public member methods
- Allows us to change how data may be stored at some future time
- Without affecting code outside the class
- Restricting a user from seeing how data is actually stored is known as data hiding
Programming Style: Class Naming Conventions
- Use nouns to name classes -- they represent objects
- Start class names with a capital letter
- Capital letter differentiates classes from methods and variables
^ top
5.2.3: Instance Variables
- Our class
Date declares 3 instance variables: month, day, year
- Each object initializes the variables to an initial value
- Default initialization value of instance variables is:
- Integer (
byte, short, int, long): 0
- Floating-point (
float, double): 0.0
- Character (
char): '\u0000'
- Boolean:
false
- Objects:
null
- Keyword private means that the variables cannot be read outside of the class
- Rule of thumb: make all data members
private
- Instance variables represent the state of the object
- Two objects can have the same state if their variables have the same value
private int month;
private int day;
private int year;
^ top
5.2.4: Instance Methods
- Instance methods are the operations that can occur on the object
- Objects use methods to send information to each other
- Syntax for declaring instance methods:
[accessModifier] returnType methodName(parameter list) {
// statements of the method
}
In general, you should declare most class methods public
However, to prevent other classes from using a method, declare it private
Name of the method combined with the parameter list form its signature
Can have many methods with the same name in a class
- However, each must have a different signature
Programming Style: Method Naming Conventions
- As mentioned before, use verbs for method names
- Appropriate since they perform an action
- Also start method names with a lower case letter
- Not required, but is a convention that professional programmers follow
Get Methods
- When variables are declared private, may still need access to them
- Use
public methods to access the data
- Called get methods (a.k.a. accessor methods)
- Use the name of the variable with the word get prepended
- For example:
public int getMonth() {
return month;
}
Set Methods
- May also need to modify private variables
- Use
public methods to modify the data
- Called set methods (a.k.a. mutator methods)
- Use the name of the variable with the word set prepended
- Allows the programmer to verify the value before setting it
- For example:
public void setDate(int mm, int dd, int yyyy) {
day = dd;
month = dd;
year = yyyy;
}
^ top
5.2.5: Defining Constructors
- Constructors are called whenever an object is created from a class
- Primary purpose is to initialize the instance variables
- Syntax for declaring constructors:
[accessModifier] ClassName(parameter list) {
// statements to initialize instance variables
// other initializing statements as needed
}
For now, use the public access modifier for all class constructors
- Other objects call the constructor when creating new objects
Constructors must use the same name and capitalization as the class name
Constructors can have zero or more parameters, just like methods
Name of the constructor combined with the parameter list form its signature
Can have many constructors in a class, but each must have a different signature
Constructor Header
- Constructors are just like member methods with the following restrictions:
- Only accessibility modifiers permitted (e.g.
public, private)
- Must use the same name as the class
- Cannot return a value -- thus no return type specified
- Can only be called using the
new operator
public Date() {
month = 12;
day = 25;
year = 2002;
}
Default Constructor
- Constructor with no parameters
- If no constructor defined, then compiler supplies one for the class
- Default constructor supplied by compiler is equivalent to:
<ClassName>() {}
As you can see, the compiler-supplied constructor does nothing
If a class defines one or more constructors, it cannot rely on the compiler-suppled constructor
Programming tip: include your own default constructor
Overloaded Constructors
- Like methods, constructors can be overloaded
- In our example, we had two constructors
public Date(int newMonth, int newDay, int newYear) {
month = newMonth;
day = newDay;
year = newYear;
}
Overloading allows appropriate initialization of objects under different conditions
^ top
5.2.6: Summary
- Classes contains three general sections:
- Instance variables
- Constructor
- Instance methods
- Instance variables store the attributes (data) of an object
- Constructors are called whenever an object is created from a class
- Instance methods are the operations that can occur on the object
- Access modifiers control access to variables, constructors and methods
private: can only be accessed by member methods of this class
public: can be accessed by member methods of any class
- Use
private for all variables and public for most methods
- Use "get" methods to return values of private variables
- Use "set" methods to control setting of new values to private variables
^ top
Exercise 5.2
Take one minute to prepare an answer the following question:
- Given a class named
Timer, which of the following is a valid definition of a constructor:
void Timer() {}
Timer Timer() {}
private final Timer() {}
Timer(Timer t) {}
public static void Timer(String args[]) {}
^ top
5.3: Creating and Using Objects
Objectives
At the end of the lesson the student will be able to:
- Code a class that creates objects from a user-defined class
- Use the methods of objects to accomplish the required tasks
|
^ top
5.3.1: Instantiating Objects
- Two steps to Instantiating an object from a class
- First step is to create a reference variable
- Must use the class name as the type
Date d;
Second step is to create the object
Use the new operator followed by the class name
Returns a reference to a new instance of the class
Reference then assigned to the variable
d = new Date();
Each object has a unique identity from the reference
Each object has its own copy of the variables declared in the class definition
Can also declare and Instantiate in one line
Date d = new Date();
Can add a method main to test the Date class
- Common practice among Java programmers
// not required -- used to test the class Date
public static void main(String[] args) {
Date d1 = new Date();
Date d2 = new Date();
d2.setDate(7, 4, 2002);
d1.showDate();
d2.showDate();
}
Creates two different objects of type Date
Each objects has its own set of data variables
Each object is referenced through its reference variable: d1 or d2
^ top
5.3.2: Two Example Classes
- Use an example to demonstrate how to define classes
- Will discuss its features in the following sections
public class Counter {
private int value; // instance variable
private int size; // instance variable
public Counter() { // default constructor
size = 100;
}
public Counter(int maxSize) { // constructor
size = maxSize;
}
public int get() { // accessor method
return value;
}
public void reset() { // mutator method
value = 0;
}
public void click() {
value = (value + 1) % size;
}
}
To Instantiate and test our class, we use another class
public class CounterTest {
public static void main(String[] args) {
Counter c1 = new Counter(); //create a Counter
Counter c2 = new Counter(100); //create a second one
c1.click(); // increment Counter c1
c2.click(); // increment Counter c2
c2.click(); // increment Counter c2 again
System.out.println("Counter1 value is " + c1.get());
System.out.println("Counter2 value is " + c2.get());
c1.reset();
System.out.println("Counter1 value is " + c1.get());
}
}
^ top
5.3.5: Accessing Private Fields
- One important note about private fields
- Any object of a particular class can access the private fields of another object of that class
- For example we could add a constructor to class
Counter
- Could use another Counter object as an argument to the constructor
public Counter(Counter c) {
size = c.size;
}
Note that c.size accesses the private field of c
^ top
5.3.3: Calling Object Methods
- To call methods of an object, code the object name followed by a period, the method name and the arguments:
objectName.methodName(argumentList);
For example, to send no arguments and return no value:
c1.click();
Is a message sent?
^ top
5.3.4: Summary
- To create an object from a class, use the
new operator
objectName = new ClassName(argumentList);
To call methods of an object, use the following syntax:
objectName.methodName(argumentList);
Objects can be part of the data for other classes
^ top
Exercise 5.3
Take one minute to prepare an answer the following question:
- An object is...
- what classes are instantiated from
- an instance of a class
- a plan for creating objects
- a reference to an attribute
- a variable
^ top
5.4: More Class Features
Objectives
At the end of the lesson the student will be able to:
- Use the
this reference
- Use
static members in programs
|
^ top
5.4.1: Objects as Method Arguments
- Java passes the value stored in a variable the same way for both primitive types and reference types
- When a method is called, value of each argument is copied to its corresponding parameter
- Thus an argument's value can never be changed within a method
- Passing a reference value has implications not present when passing primitive values
- Called method gets access to the exact same object passed by the calling method
- Situation is shown in the following diagram:

For Example
- Following program demonstrates passing a reference value (e.g. String)
- Note that the method call and parameter declaration are similar to primitive types
public class PassMessage {
public static void main(String[] args) {
String s1 = "Original message";
displayMsg(s1);
}
public static void displayMsg(String msg) {
System.out.println("In displayMsg: " + msg);
}
}
Since the original message displays in the displayMsg method, we successfully passed a reference type
^ top
5.4.2: Instance Methods and this
- Instance methods belong to every object of the class
- Can only be invoked on objects of the class
- Body of an instance method can access all members (including static member)
- How can this work?

- All methods are passed an implicit parameter named
this
- For instance:
get()
Is called as if it had the parameter this
get(this)
this refers to the object that calls the method
Even though passed implicitly, can still use the this parameter
Used with the dot '.' operator like any other object reference
this.size
Use of this reference is optional unless needed to clarify variable scope
For instance, we could have defined the overloaded constructor of Counter
public Counter(int size) { // constructor
this.size = size;
}
Need this to differentiate between instance variable size and parameter size
^ top
5.4.3: Static Methods and Fields
- A static method does not operate on an object
- Receives all its data as arguments
- If declared
public, static methods are referred to as general purpose methods
- Implies that the method performs a general-purpose task
- Often used to construct dialog boxes and in Math methods
- Classes may also have static fields
- Implies there is just one value for any object in a class
Example Using static Members
- Classic example: keep track of how many objects of a class are created
- Cannot use an instance variable in the class definition
- Which instance variable do you use?
- Could use another class with an instance variable
- However, a more elegant solution is to use a static variable
- Such a variable belongs to the class and not to any object
- Let's add an object count to the
Counter class
- First need to define a static variable
- Declared and initialized just like instance variable but with the keyword
static
private static int numObjs = 0;
Need to increment the variable whenever a new object is instantiated
Can add an increment statement to the object constructors
public Counter2() { // default constructor
size = 110;
numObjs++;
}
public Counter2(int maxSize) { // constructor
size = maxSize;
numObjs++;
}
Also need a method to retrieve the count
public static int numObjs() {
return numObjs;
}
Note that a static method does not have a calling object reference (i.e. this)
Thus cannot refer to a (non-static) instance variable of the class
Likewise, a static method cannot call a non-static method of the class
Putting everything together we get the Counter2 class
public class Counter2 {
private int value; // instance variable
private int size; // instance variable
private static int numObjs = 0;
public Counter2() { // default constructor
size = 100;
numObjs++;
}
public Counter2(int maxSize) { // constructor
size = maxSize;
numObjs++;
}
public int get() { // accessor method
return value;
}
public void reset() { // mutator method
value = 0;
}
public void click() {
value = (value + 1) % size;
}
public static int numObjs() {
return numObjs;
}
}
- Must also update the CounterTest class to use the new features
public class Counter2Test {
public static void main(String[] args) {
Counter2 c1 = new Counter2(); //create a Counter
Counter2 c2 = new Counter2(100); //create a second one
c1.click(); // increment Counter c1
c2.click(); // increment Counter c2
c2.click(); // increment Counter c2 again
System.out.println("Counter1 value is " + c1.get());
System.out.println("Counter2 value is " + c2.get());
c1.reset();
System.out.println("Counter1 value is " + c1.get());
System.out.println(Counter2.numObjs());
}
}
Further Information
Designing with Static Members
^ top
5.4.4: Garbage Collection and Finalizers
Garbage Collection
- Garbage collection returns memory to system
- Java performs garbage collection automatically
- An object is marked for garbage collection if no references to object
- Can manually choose to run the garbage collector
System.gc();
Finalizing Objects
Before garbage collection, Java gives an object a chance to clean up
Known as finalization and runs the finalize method
Defined in java.lang.Object
- Receives no parameters
- Returns void
^ top
5.4.5: Packages
- A way of grouping and naming a collection of related classes
- Can serve as a library of classes
- Do not have to be in the same directory as your program
- Packages organized in a hierarchy -- similar to file directories
- Dot '
.' operator used to uniquely identify package members
- Fully-qualified package name describes the location of the files
Using Packages
- One way to use packages is to use the fully-qualified type name
- For example:
java.util.StringTokenizer st =
new java.util.StringTokenizer(s);
Quickly becomes tedious so use the import statement instead
Syntax:
import <fully-qualified type name>;
To use classes from a package, put an import statement at the start of the file
For example:
import java.util.StringTokenizer;
Can also use "wildcard" notation to select all packages
import java.util.*;
Can now use the simple type name (i.e. class name)
StringTokenizer st = new StringTokenizer(s);
Further Information
Creating and Using Packages: from the Java Tutorial
^ top
Exercise 5.4
Take one minute to prepare an answer the following questions.
- What would be the results of attempting to compile and run the following program?
class MyClass {
static MyClass ref;
String[] args;
public static void main(String[] args) {
ref = new MyClass();
ref.func(args);
}
public void func(String[] args) {
ref.args = args;
}
}
^ top
Wrap Up
^ top
Home
| WebCT
| Announcements
| Schedule
| Expectations
| Syllabus
Help
| FAQ's
| HowTo's
| Links
Last Updated: October 01 2003 @17:21:38
|