Docsity

Lecture Slides on Using Java Objects | CS 230, Study notes of Data Structures and Algorithms

Toggle sidebar
bg1
USING JAVA OBJECTS
CS230 - Reading LD C Ch. 3 1
• Objects and References
• The String Class
• Using Packages
• The Random Class
• The Math Class
• Enumerated Types
• Wrapper Classes
• Formaing Output
2
3.1 – Objects…
Generally, we use the new operator to create an object
name1 = new String ("Steve Jobs");
This calls the String constructor,
which is a special method that sets up the object
Creating an object is called instantiation
An object is an instance of a particular class
3
3.1 – Object References
A primitive variable contains the value it self,
but an object variable contains the addres s of the object
An object reference can be thought of
as a pointer to the lo cation of the obj ect
We usually depict a r eference graphically
"Steve Jobs"
name1
num1 38
4
3.1 – Understanding the Assignment
For primitive types,
assignment takes a copy of a value
and stores it in a variable
num1 38
num2 96
Before:
num2 = num1;
num1 38
num2 38
After:
name2 = name1;
name1
name2
"Steve Jobs"
"Steve Wozniak"
"Steve Wozniak"
name1
name2
"Steve Jobs"
For object references,
assignment copies the address
Two or more references that refer to the same object are called aliases
So, one object can be accessed using m ultiple reference variables (!!)
Aliases can be useful, but dangerous: should be managed carefully
Changing an object through one reference cha nges it for all of its aliases,
because there is really only one object
Execute:
pf3
pf4
pf5

Partial preview of the text

Download Lecture Slides on Using Java Objects | CS 230 and more Study notes Data Structures and Algorithms in PDF only on Docsity!

USING JAVA OBJECTS

CS230 - Reading LDC Ch. 3 1

• Objects and References

• The String Class

• Using Packages

• The Random Class

• The Math Class

• Enumerated Types

• Wrapper Classes

• Formaing Output

3.1 – Objects…

Generally, we use the new operator to create an object

name1 = new String ("Steve Jobs");

This calls the String constructor ,

which is a special method that sets up the object

Creating an object is called instantiation

An object is an instance of a particular class

3.1 – Object References

A primitive variable contains the value itself,

but an object variable contains the address of the object

An object reference can be thought of

as a pointer to the location of the object

We usually depict a reference graphically

name1^ "Steve^ Jobs"

num1 38

3.1 – Understanding the Assignment

For primitive types,

assignment takes a copy of a value

and stores it in a variable

num1 38

num2 96

Before:

num2 = num1;

num1 38

num2 38

After:

name2 = name1;

name

name

"Steve Jobs"

"Steve Wozniak"

"Steve Wozniak"

name

name

"Steve Jobs"

For object references ,

assignment copies the address

Two or more references that refer to the same object are called aliases

So, one object can be accessed using multiple reference variables (!!)

Aliases can be useful, but dangerous: should be managed carefully

Changing an object through one reference changes it for all of its aliases,

because there is really only one object

Execute:

3.1 – Garbage Collection

When an object no longer has any valid references to it,

it can no longer be accessed by the program

The object is useless, and therefore is called garbage

Java performs automatic garbage collection periodically, recycling

an object's memory space to the system for future use

In other languages, the programmer is responsible for performing

garbage collection

Garbage collection is great,

but may introduce unexpected delays in the execution of a program

3.2 – String Methods

Because strings are so common,

we don't have to use the new operator to create a String object

name1 = "Steve Jobs”;

Immutable String: Once a String object has been created,

neither its value nor its length can be changed

However, several methods of the String class

return new String objects that are modified versions of the original

It is occasionally helpful to refer to a particular character within a string

This can be done by specifying the character's numeric index

In the string "Hello",

the 'H' is at index 0 and

the 'o' is at index 4 H^0 e^1 l^2 l^3 o^4 \

3.2 – StringMutation.java //******************************************************************** // StringMutation.java Java Foundations // // Demonstrates the use of the String class and its methods. //******************************************************************** public class StringMutation { //----------------------------------------------------------------- // Prints a string and various mutations of it. //----------------------------------------------------------------- public static void main (String[] args) { String phrase = "Change is inevitable, except from vending machines."; String mutation1, mutation2, mutation3, mutation4; mutation1 = phrase.concat (".. "); mutation2 = mutation1.toUpperCase(); mutation3 = mutation2.replace ('E', 'X'); mutation4 = mutation3.substring (3, 30); System.out.println ("Mutation #4: " + mutation4); System.out.println ("Mutated length: " + mutation4.length()); } } 8 3.3 – Class Libraries

A class library is a collection of classes

that we can use when developing programs

The Java standard class library

is part of any Java development environment:

http://java.sun.com/j2se/1.5.0/docs/api/

Its classes are not part of the Java language per se,

but we rely on them heavily

Various classes we've already used (System , Scanner, String)

are part of the Java standard class library

Other class libraries can be obtained

through third party vendors, or you can create them yourself

3.5 – Very useful: The Math Class

The Math class is part of the java.lang package

Math functions include

n absolute value n square root n exponentiation n trigonometric functions

The methods of the Math class are static methods (aka class methods )

Static methods can be invoked through the class name –

no object of the Math class is needed

discriminant = Math.pow(b, 2) - (4 * a * c); root1 = ((-1 * b) + Math.sqrt(discriminant)) / (2 * a); root2 = ((-1 * b) - Math.sqrt(discriminant)) / (2 * a); 14 3.7 – Enumerated Types

An enumerated type establishes all possible values for a variable

by enumerating them (IMH!)

The values are identifiers of your own choosing

Helps program readability! (How would you represent the 4 seasons?)

This declaration creates an enumerated type called Season

enum Season {winter, spring, summer, fall};

Once a type is defined, a variable of that type can be declared

Season time;

and it can be assigned a value

time = Season.fall;

Enumerated types are type-safe –

you cannot assign any value other than those listed

3.7 – Ordinal Values and Names

Internally, each value of an enumerated type is stored as an

integer, called its ordinal value

The first value in an enumerated type has an ordinal value of 0,

the second 1, and so on

However, you cannot assign a numeric value to an enumerated

type, even if it corresponds to a valid ordinal value

The declaration of an enumerated type is a special type of class,

and each variable of that type is an object

The ordinal method returns the ordinal value of the object

The name method returns the name of the identifier

corresponding to the object's value

3.7 – IceCream.java //******************************************************************** // IceCream.java Java Foundations // // Demonstrates the use of enumerated types. //******************************************************************** public class IceCream { enum Flavor {vanilla, chocolate, strawberry, fudgeRipple, coffee, rockyRoad, mintChocolateChip, cookieDough} //----------------------------------------------------------------- // Creates and uses variables of the Flavor type. //----------------------------------------------------------------- public static void main (String[] args) { Flavor cone1, cone2; cone1 = Flavor.rockyRoad; System.out.println ("cone1 value: " + cone1); System.out.println ("cone1 ordinal: " + cone1.ordinal()); System.out.println ("cone1 name: " + cone1.name()); for (Flavor cone: Flavor.values()) { System.out.println ("cone value: " + cone); } }

3.8 – Wrapper Classes

Are the primitive types objects?

The java.lang package contains wrapper classes

that correspond to each primitive type

Primitive Type Wrapper Class byte Byte short Short int Integer long Long float Float double Double char Character boolean Boolean void Void 18 3.8 – Wrapper Classes

An Integer object which represents the integer 40 as an object:

Integer age = new Integer(40);

An object of a wrapper class can be used

in any situation where a primitive value will not suffice

For example, some objects serve as containers of other objects

Primitive values could not be stored in such containers, but wrapper

objects could be

Wrapper classes also contain static methods that help manage the

associated type

For example, the Integer class contains a method

to convert an integer stored in a String to an int value:

num = Integer.parseInt(str);

The wrapper classes often contain useful constants as well

For example, the Integer class contains MIN_VALUE and MAX_VALUE

which hold the smallest and largest int values

3.8 – Autoboxing and Unboxing

Autoboxing is the automatic conversion of a primitive value

to a corresponding wrapper object

Integer i;

int num = 42;

i = num;

The assignment creates the appropriate Integer object

The reverse conversion ( unboxing )

also occurs automatically as needed