lecture 2: objects, references, constructors, scope, wrappers, & debugging suggestions. java for...

96
Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient Java for the Impatient

Upload: bonnie-may

Post on 04-Jan-2016

230 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Lecture 2: Objects, References, Constructors, Scope,

Wrappers, & Debugging Suggestions.

Java for the ImpatientJava for the Impatient

Page 2: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Announcements

Web page:

http://www.cc.gatech.edu /projects/gsams-java

Please respond to thesurveys; it helps all of us.

Page 3: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Posted QuestionsDeclaration and use of counting variables outside of loop structure?

Yes; safe for interpretedlanguage such as Java (with gc & no registers).

Allows for common sense.

Further: encourages consideration of variablecreation and scoping.

Page 4: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Posted QuestionsWhat else was wrong with if/else structurefrom previous slides?

As noted last week, use of constantsfor grade codes (e.g., A == 90+)would enable efficient maintenance of program.

Page 5: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Posted Questions (cont’d)

Use of NTEmacs editor?

Not covered herein. Links:

http://www.xemacs.org

http://www.cc.gatech.edu /classes/cs1502 /ntemacs/ides.html

Ask about our lab materials

Page 6: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Posted Questions (cont’d)

Improve size of font!

How’s this?

Also, you might refer to printed slides.

Feedback mechanism?

Page 7: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

• References and Pointers in Java– Declaring objects– References vs. pointers– Differences between primitives and objects– Invoking methods belonging to objects

• Instantiating and Initializing Objects• Class and Instance Variables

Lecture Topics

Page 8: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Introduction to Programming, Lecture 3

Last lecture, we looked at a model for a box:

class Box { int iLength; int iWidth; int iHeight;

public void setLength (int iNewLength) { util.ASSERT (iNewLength > 0,

“iNewLength <= 0”); iLength = iNewLength; } // of setLength

public int getLength ( ) { return (iLength); } // of getLength

Page 9: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

public void setWidth (int iNewWidth) { util.ASSERT (iNewWidth > 0,

“iNewWidth <= 0”); iWidth = iNewWidth; } // of setWidth

public int getWidth ( ) { return (iWidth); } // of getWidth

public void setHeight (int iNewHeight) { util.ASSERT (iNewHeight > 0, “iNewHeight <= 0”); iHeight = iNewHeight; } // of setHeight

Page 10: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

public int getHeight ( ) { return (iHeight); } // of getHeight

public int getVolume ( ) { return ( getLength( ) * getWidth( )

* getHeight( ) ); } // of getVolume} // of class Box

Page 11: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Introduction to Programming, Lecture 3

We found that to use this class, we had to ‘declare an object’.

“Declaring an object” really means declaring a reference to an object.”

A reference is an implict (or automatic) pointer that can point to an object of the specified class.

Declaring Objects

Page 12: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Declaring ObjectsThus, the code: Box shoeBox;

• does not create an object of class Box.• does create a reference (or ptr) shoeBox that can point to an object of class Box.• gives us what amounts to a ptr to a Box which is null:

shoeBox

Page 13: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

• To make the reference shoeBox be not null, it is necessary to instantiate it, e.g.,

shoeBox = new Box( );

Box shoeBox;

shoeBoxBox

Instance

shoeBox

Objects & References

Page 14: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

When Java encounters the keyword “new”, it allocates space in memory for an instance of that object. Now, shoeBox refers to an instance of class Box, i.e., an object.

Objects & References

Note that the instance (or object) “gets” everything defined in class Box. It has unique copies of all the variables. (Method are shared at byte code level.)

Page 15: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

shoeBox

The data fields (“attributes”):int iLength;int iWidth;int iHeight;

What can be done to that data(“methods”):public void setLength (int iNewLength)public int getLength ( )public void setWidth (int iNewWidth)public int getWidth ( )public void setHeight (int iNewHeight)public int getHeight ( )public int getVolume ( )

(a reference

to an object

of class Box)

A closer look:

Objects & References

David Dagon:(Cautionary Note: Here, we suggest that each object gets a unique copy of each method. Although each object is allocated unique memory space for variables, Java efficiently shares methods in common with all objects. For now, you might find it helpful to picture objects in the manner, even though it’s not technically what happens with the heap’s method space in the Java Virtual Machine.)

David Dagon:(Cautionary Note: Here, we suggest that each object gets a unique copy of each method. Although each object is allocated unique memory space for variables, Java efficiently shares methods in common with all objects. For now, you might find it helpful to picture objects in the manner, even though it’s not technically what happens with the heap’s method space in the Java Virtual Machine.)

Page 16: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Box shoeBox = new Box();Box cdBox = new Box();Box present = new Box();

The data fields (“attributes”):int iLength;int iWidth;int iHeight;

What can be done to that data(“methods”):public void setLength (int iNewLength)public int getLength ( )public void setWidth (int iNewWidth)public int getWidth ( )public void setHeight (int iNewHeight)public int getHeight ( )public int getVolume ( )

shoeBoxshoeBox

The data fields (“attributes”):int iLength;int iWidth;int iHeight;

What can be done to that data(“methods”):public void setLength (int iNewLength)public int getLength ( )public void setWidth (int iNewWidth)public int getWidth ( )public void setHeight (int iNewHeight)public int getHeight ( )public int getVolume ( )

cdBoxcdBox

The data fields (“attributes”):int iLength;int iWidth;int iHeight;

What can be done to that data(“methods”):public void setLength (int iNewLength)public int getLength ( )public void setWidth (int iNewWidth)public int getWidth ( )

. . .

presentpresent

Each time we instantiatea Box, therefore, we get a unique copy to work with. This is one of the most powerful aspect of Object-Oriented Programming!

Objects & References

Page 17: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

1. all objects are dynamic data.

2. because all objects are dynamic, Java “knows” that, whenever we reference an object, it must “follow the pointer”.

For example:

Java: shoeBox.setLength(35);

Pseudocode:

shoeBox^.setLength(35)

What do we conclude from this?

Page 18: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Java is advertised as “having no pointers.”

In reality, Java is mostly pointers! Every non-primitive datum must be an object. All objects are dynamic data, accessible via references. And references are really implicit pointers.

Java does not have explicit pointers. Outside of JNI, there exists no way to explicitly manipulate pointers. There is no explicit dereferencing operator.

References vs. Pointers

Page 19: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Introduction to Programming, Lecture 3

Distinguish between primitives and objects.

Assignment with Primitives:

Code: Memory:

int x; x

int y;

x = 5; x=5

y = x;

yx

x=5 y=5

y

Objects and References

Page 20: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Assignment with References to Objects:

Box box1;Box box2;

box1box2

box1 = new Box(8, 5, 7);

L=8, W=5, H=7

box1

box2

Objects and References

Memory: Code:

box2 = box1;

L=8, W=5, H=7

box2box1

Page 21: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

L=3, W=9, H=2

box1 = new Box(3, 9, 2); box1

box2

box1

box2

L=8, W=5, H=7

L=3, W=9, H=2

L=8, W=5, H=7

box1 = box2;// Old reference lost!

Objects and References

Page 22: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

• Given what we’ve learned about objects, it follows that methods must be invoked with respect to an object or class. There are a few restrictions:

1. Invocation must be unambiguous re: which object or class the method is to act.

2. If the method call appears inside a class, then that class is presumed to contain the appropriate method

Calling Methods

Page 23: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

class WallstreetJitters {

public void panicSell ( ) { FedResChair greenspan = new FedResChair(); if (greenspan.raisesInterest())

{ buyOnMargin(); }

else{

sellAllStock();}

} // of panicSell} // of WallstreetJitters

FORMAT: <object reference>..<method name>

The class FedResChair

must have this method!

Calling Methods

These methods must appear in WallstreetJitters class!

If the method is NOT inside the class where method declared, then the object must be specified.

Page 24: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Questions?• References and Pointers in Java• Instantiating and Initializing Objects

NEXT UP . . . • Constructors and Initialization of Instance Variables

• Method Signatures and Overloading• Creating Object Instances• Class and Instance Variables

Page 25: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Motivation:We need a means of initializing the attributes of a new object (or“instance”) when it is created.

Constructors

Example:public Box (int iNewLength, int iNewWidth, int iNewHeight) { setLength (iNewLength); setWidth (iNewWidth); setHeight (iNewHeight);} // of constructor

Means:“Constructor methods” that are invoked automatically upon“instantiation” (creation) of new object.

Page 26: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

ConstructorsNote: Constructor method has same identification as the class.

Can now do: Box subwooferBox = new Box (46, 46, 82);

Equivalent to (but better than) doing: Box subwooferBox = new Box; subwooferBox.setLength(46); subwooferBox.setWidth(46); subwooferBox.setHeight(82);

Page 27: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

A class may have more than one constructor.

If so, then each constructor must have unique formal parameter list.

Constructor calls must match one of the available constructors

Terminology: Creating multiple methods with same identifier is called “method overloading.”

We can:String strInput1 = new String ();String strInput2 = new String (“A valid constructor.”);

Result:strInput1 will be an empty String (with the value ““)strInput2 will be a String containing “A valid constructor.”

ConstructorsGiven: public String ( ) public String (String value)

Page 28: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

class Person { String strName; int iAge;

public Person (String strNewName){ setName (strNewName); } // of constructor

public Person (String strNewName, int iNewAge) { setName (strNewName); setAge (int iNewAge); } // of constructor

public void setName (String strNewName){ strName = strnewName; } // of setName

public void setAge (int iNewAge) { iAge = iNewAge: } // of setAge} // of Person

Note that theconstructors call

the modifiers

Page 29: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Can now create a new Person via: Person guitarist1 = new Person (“Clapton”); Person guitarist2 = new Person (“Hendrix”, 27); Determining which constructor to invoke requires unique signature.

Signature means “identifier and parameter list”

Thus, one cannot do: public Person (String strNewFirstName) { . . . } // of constructor

public Person (String strNewLastName) { . . . } // of constructor

due to ambiguity.

Java Constructors

Page 30: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Default constructors:

If you don’t define a constructor, a default constructor will be automatically invoked.

The default constructor expects no parameters.

The default constructor initializes instance variables to standard Java default values (0 for nums, false for booleans, null for references).

Default constructor equivalent to:

public Person ( ) { } // of default constructor

You can override this by creating your own default constructor (no params) that does contains code.

Java Constructors

Page 31: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Constructors CANNOT have return values: Do NOT do this:

public int Person ( ) { . . . // whatever code } // of constructor

public void Person ( ) { . . . // whatever code } // of constructor

Java Constructors

A return value (including void) means that the method is NOT a constructor, and it won’t be auto-invoked.

Page 32: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Involves three things:

1. Creating the reference: Box thisBox ;

2. Instantiating the object: thisBox = new Box( );

OR do first two steps at once, e.g., Box thisBox = new Box( )

3. Having constructor(s) set initial values:

public Box (int iNewLength, int iNewWidth, int iNewHeight) { setLength (iNewLength); setWidth (iNewWidth); setHeight (iNewHeight); } // of constructor

With an appropriate constructor, we can do all three at once:

Box thisBox = new Box (10, 5, 25);

Creating Instances of Classes

Page 33: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

A distinction that applies to both variables and methods

An instance <variable or method> is one that belongs to each object of a class.

A class <variable or method> is one that belongs only to the class itself.

The keyword static:

• indicates a class variable or class method.

• absence of the keyword static indicates an instance variable or instance method.

Instance vs. Class Declarations

Page 34: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Declares a strName String for each instance. Thus, each Human will have its

own name. But . . . Also declares an iPopulation counter for each instance of Human.

Thus, each Human will have its own iPopulation variable, each having a value of 1. This makes no sense!

Instance vs. Class Variables

Suppose we wanted to track the total number of objects created.

Consider:

class Human { String strName; int iPopulation = 0;

public Human (String strName) { this.strName = strName; iPopulation++; //WRONG! } // of constructor

} // of Human

Page 35: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

class Human { String strName; static int iPopulation = 0;

public Human (String strName) { this.strName = strName; iPopulation++; } // of constructor

} // of Human

Instance vs. Class Variables

one change

As we know, this declares a strName String for each instance.

Thus, each Human will have its own name.

NOTE: Each Human does not get an iPopulation counter.

This declares a single iPopulation counter for the class Human itself. It is a class variable.

Thus, each Human will increment this single shared counter by 1.

Page 36: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Instance vs. Class Variables:When to Use

Use instance variables whenever each object should have its own variable.

E.g., attributes of the particular object.

Use a class variable whenever the class itself should maintain a single copy of datum pertaining to all instances of the class.

E.g.,

population counts. summary data. assigning serial numbers. shared resources.

Page 37: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Instance vs. Class Variables

Constants Revisited:

class ConstantExample { final int iMAXSIZE = 10; } // of ConstantExample

class ConstantExample { static final int iMAXSIZE = 10; } // of ConstantExample

Declares a different-but-identical constantfor each instance of the class.

Wasteful with zero benefit.

Declares a single constant for use by all instances of the class.

Page 38: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Questions?• Constructors• Class members vs. instance members

NEXT UP . . .

• Reference– Reference review– == and equals()– Parameter passing

• Strings and debugging– Strings and regular objects– Strings and identity– toString() and debugging main()

• Arrays

Page 39: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Objects and ReferencesObjects and ReferencesAssignment with References to Objects:

Two logical operations available:

1. The operator = (assignment)

• It assigns references to objects, i.e., it manipulates the pointers.• Used in the form: str1 = str2

2. The method clone( )

• It copies the object itself. • Used in the form: str1 = str2.clone( ); • Not available for all types (requires cloneable interface; interfaces to be discussed later).

Page 40: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Two references to a single area of memory

Creates a new area in memory so each named reference points to its own object

Assignmentoperator: =

clone();

Objects and ReferencesObjects and References

Page 41: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Assignment with References to Objects:

Given this:str1 str2

doody

howdy

The statement str1 = str2; would give:

str1

str2doody

howdy

But str1 = str2.clone(); would give:

str1

str2 doody

doody

Objects and ReferencesObjects and References

Two distinct areas of memory

Two references to one object

Page 42: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Equality with Primitives:

int iBraves;int iPhillies;iBraves = 11;iPhillies = 3;

System.out.println(iBraves = = 11); // prints trueSystem.out.println(iPhillies = = 3); // prints trueSystem.out.println(iBraves = = iPhillies); // prints false

iBraves = iVikings;

System.out.println(iBraves = = 3); // prints trueSystem.out.println(iPhillies = = 3); // prints trueSystem.out.println(iBraves = = iPhillies); // prints true

System.out.println(iBraves > iPhillies); // prints false (!)

11 3

iBraves iPhillies

3 3

iBraves iPhillies

Objects and ReferencesObjects and References

Page 43: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Equality with References to Objects:

Two different logical tests available:

1. The operator = = (equality)

• It evaluates whether two references point to the same object.

2. The method equals( )

• It evaluates whether the internal state (i.e., contents) of one object is identical to the internal state of another object.

• It is a special method built-in to the class Object, and is available to all classes you create. In practice you will want to code a version of equals() in your classes, so that you can compare objects.

Objects and ReferencesObjects and References

For primitives

For objects

Page 44: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Objects and ReferencesEquality with References to Objects:

Box box1 = new Box(8, 5, 7);Box box2 = new Box(8, 5, 7);

System.out.println(box1 == box2); // prints false// does box1 reference the same // object referenced by box2?

System.out.println (box1.equals(box2)); // prints true

// does box1 reference an object // having the same contents as// the object referenced by box2?

Page 45: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Objects and References

.equals( ) compares if the objects have the same content!

box1

box2

L=8,W=5,H=7

L=8,W=5,H=7

‘==‘ compares if these references point to the same place in memory!

Box box1 = new Box(8, 5, 7);Box box2 = new Box(8, 5, 7);

Page 46: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Note: we must

decide whatconstitutesequivalency

“Casting”(covered later)

Objects and ReferencesThe equals( ) method is therefore useful in comparing objects. Here’s an example of a typical equals( ) method:

class Box{// same accessor/modifier methods seen in previous slides

public boolean equals (Object oTemp) { boolean bSame = false; if (oTemp instanceof Box) { Box bTemp = (Box) oTemp; if ( getLength() == bTemp.getLength() && getWidth() == bTemp.getWidth() && getHeight() == bTemp.getHeight() ) bSame = true; } return bSame;}// equals

Page 47: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Explanation of the typical equals( ) method:

1. The keyword ‘instanceof’ merely determines whether or not a reference is of a type of class.

String strExample = “Hello”;

if (strExample instanceof String)System.out.print (“It’s a String!”);

We will cover this keyword in more detail later.

2. The steps taken to verify the identity of two objects is inherently based on their context. In the example, two boxes were deemed identical if they had the same dimensions. Other tests could have been used.

Objects and References

Page 48: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Objects and ReferencesAs Regards the Identity of Objects. There are essentially four tests we can use to compare the identity of objects.

Reflexive: for any reference value x, x.equals(x) should return true.

Symmetric: for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.

Transitive: for any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.

Consistency: for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false. (I.e., it wasn’t just a fluke.)

Why is this important? If you forget to create your own equals() method in a data class, you can still compare the objects with equals(), but the method ‘defaults’ to the most stringent equivalency test possible. That is, equals() will return true only if the two references point to the exact same location in memory.

Page 49: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Java ParametersJava ParametersPseudocode has 3 basic kinds of parameters:

inoutin/out

You choose between them as appropriate.

Java provides two kinds of parameters:

pass-by-value (or pbV): for passing primitives. pass-by-constant-reference (or pbCR): for passing objects.

• The compiler chooses for you based on what is being passed.

• In Java, you have no choice.

Page 50: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Java ParametersFor all practical purposes, Java provides only the functionality of an in parameter.

pass-by-value: • what an in parameter “really is”, i.e., a value is passed in to the called method.

• the called method gets its own copy of the original.

pass-by-constant-reference: • when the call is made, the current value of the object is referenced.

• the called module can access that value but cannot change it... only its temp copy of it can be changed...

Subtle technical difference.

Zero practical difference.

Page 51: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Java ParametersJava ParametersGiven the method:

public void swap (int iOne, int iTwo) { System.out.println (iOne, + “, “, + iTwo); // line a int iTemp = iOne; iOne = iTwo; iTwo = iTemp; System.out.println (iOne, + “, “, + iTwo); // line b} // of swap

Then, executing the code fragment:

int iThis = 5;int iThat = 6;System.out.println(iThis, + “, “, + iThat); // line cswap (iThis, iThat);System.out.println(iThis, + “, “, + iThat); // line d

Gives the output:

5, 6 ( from fragment line c )5, 6 ( from swap line a )6, 5 ( from swap line b )5, 6 ( from fragment line d )

Page 52: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Given the method:

public void test (String strInput) { System.out.println (strInput); // line a strInput = “new string”; System.out.println (strInput); // line b} // of test

Then, executing the code fragment:

String strTemp = “original string”;System.out.println(strTemp); // line ctest(strTemp);System.out.println(strTemp); // line d

Gives the output:

original string ( from fragment line c )original string ( from test line a )new string ( from test line b )original string ( from fragment line d )

Java ParametersJava Parameters

Page 53: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

If only have in parameters... what to do?!? Think OO!

• Data and methods are encapsulated, i.e., we want all access to, and modification of, data to belong only to the object itself via the object’s methods (provided by its class).

• Within a class, data is accessible to methods without going through parameters.

• Access from outside should be only by asking the object to “do it for you” via its methods:

• accessor ( “get” ) methods: i.e., functions that return a value• modifier ( “set” ) methods: i.e., procedures that change data state.

• From outside the object, gain access via methods.

• Functionality of an out param via modifier methods.

• Functionality of an in/out param via an accessor methods (for the in) and and a modifier (for the out).

Java ParametersJava Parameters

Page 54: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Java parameter variables are (as you’d expect) declared as part of the method to which they are used to provide data.

Thus, they are considered local variables with respect to their method.

This means that they are automatically created when the method is called (and its frame is pushed onto the stack), and ...

They are automatically deallocated when their method terminates and its frame is popped off the stack.

Unlike standard local variables, they do not have to be instantiated or initialized, as those aspects are handled when the actual parameters are passed to the method.

Java ParametersJava Parameters

Page 55: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

ScopeScopeLocal variables (declared as a part of method):

• Can be seen only from within their method.

• Outside of their method, their identifiers have no meaning.

Instance and Class variables (declared as part of a class, but not within a particular method):

• Can be seen from anywhere in the instance.

• This means they can be seen from within methods defined within the class without passing them to the method as parameters.

• May or may not be visible beyond (soon).

Within a method, local variable identifiers take precedence over instance variable IDers

Page 56: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

We want to refer to the instance variable strName inside the method, but this code fails!

WRONG!

Preventing Identifier AmbiguityPreventing Identifier Ambiguity

Given:

class Person { String strName;

. . .

public void setName (String strName) {

strName = strName;

} // of setName

Inside the method, the String strName refers to the String in the method signature. This creates a problem: which strName is which?

Page 57: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Solutions:• Rename the formal parameter:

public void setName (String strNewStringName) {

strName = strNewStringName;

} // of setName

• Use the keyword this to refer to “current object”

public void setName (String strName) {

this.strName = strName;

} // of setName

Preventing Identifier AmbiguityPreventing Identifier Ambiguity

Page 58: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Summary so far• Reference

– When comparing primitives (int, float, etc.), use ‘==‘– When comparing objects (String, or any class you

create), use the equals() method– When you create a class that serves as a data type or

record, remember to include an equals() method

All parameters are in parameters. To change state of object, call modifier methods from within body of methodWhen ids are ambiguous, the most local one takes priority

Page 59: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Strings vis-a-vis ObjectsStrings vis-a-vis Objects

Every String is an instance of Java’s built-in class String.

Thus, Strings are objects.

Java provides extra support for Strings as a convenience because of the frequency with which Strings are used.

Three obvious String support features:

1. You need not explicitly instantiate Strings with the ‘new’ keyword.

Java automatically instantiates a String object when it encounters a text string within double-quotes.

For example . . .

Page 60: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Strings vis-a-vis ObjectsStrings vis-a-vis ObjectsAssignment w/References to Strings/Objects: Code: Memory:

String str1;Box box1;

str1box1

str1 = “Hello World”;

box1 = iLn, iWd, iHt;

Hello World str1box1

ERROR: must use new “new” and call constructorERROR: must use new “new” and call constructor

Page 61: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

str1 = “Hello World”;box1 = new Box(iLn, iWd, iHt);

Hello World

str2 = new String();

str2 = “Glib Folksies”;

str2

str2

“default”

Glib Folksies

str1box1 iLn, iWd, iHt

?default?

Strings vis-a-vis ObjectsStrings vis-a-vis Objects

Strings are immutable

Page 62: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Again, Java automatically creates a new String object whenever it encounters text within double-quote marks.

Thus, the code:

String str1 = “Hello World”;

accomplishes three things:

1. It creates str1 as a reference to a String. 2. It creates an instance of a String. 3. It initializes that String to “Hello World”.

This is inconsistent with how Javatreats standard objects.

With standard objects, you must explicitly: instantiate (via new), and initialize (via a constructor).

Strings vis-a-vis ObjectsStrings vis-a-vis Objects

Page 63: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

3. Several predefined methods provided in built-in class String. Among them are:

length( ) // a string knows its length charAt(iIndex) // returns letter at position iIndex; 1st char is position 0 substring(iStartIndex) // returns the // substring from position

// iStartIndex to end of string substring(iStartIndex, iEndIndex) // returns // substring from position iStartIndex // until but NOT INCLUDING position iEndIndex

String StuffString Stuff1. You need not explicitly instantiate Strings.

2. The ‘+’ operater overloaded for Strings, to support concatenation, e.g.,

System.out.println(“This string is an example of” + “ one that is too long to fit on one line. Your TAs take off points” + “ for lines that exceed 80 column characters.”);

Page 64: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Strings Stuff -- ExamplesStrings Stuff -- Examples

H e l l o0 1 2 3 4

char c = strExample.charAt(1); // c gets ‘e’

String strBritishHowdy = strExample.substring(1);

strBritishHowdy ---> “ello”

String strLectureRoomTemperature = strExample.substring(0, 4);

strLectureRoomTemperature --> “Hell”

String strExample = “Hello”;

Page 65: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Also . . .

One cannot change contents of a String object. (We say: “Strings are immutable”.)

You may think you are modifying a String. But, what happensin memory is:

* a new String is created * your old String may be ‘garbage collected’; you no longer have a reference to the old String

For example:

Hello World str1

String str1 = “Hello World”

str1 = str1.substring(4)

Hello World

o World

str1

Strings vis-a-vis ObjectsStrings vis-a-vis Objects

Page 66: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Objects and References: Objects and References: The special case of StringThe special case of String

Caution: In the next few slides, we will cover what is one of the more confusing part of Java for new students. If you get lost, just remember what we’ve covered so far:

1. When comparing primitives (int, float, etc.), use ‘==‘ 1. When comparing primitives (int, float, etc.), use ‘==‘

2. When comparing objects (String, or any class you create), use 2. When comparing objects (String, or any class you create), use the equals() method. the equals() method.

3. When you create a class that 3. When you create a class that serves as a data type or record, serves as a data type or record, remember to include an remember to include an equals() method.equals() method.

In the slides ahead we will note some rare exceptions where the ‘==‘ comparison will work for objects.

Page 67: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Objects and References: Review of the normal case

Remember the general pattern of our previous example:box1 = new Box(1, 2, 3);box2 = new Box(8, 5, 7);box1 = box2;

System.out.println(box1 = = box2); // prints true// Does box1 reference the same // object that box2 references?

System.out.println(box1.equals(box2)); // prints true// Does box1 reference an object that has // the same contents// as the object referenced by box2?

box1 box2

L=8, W=5, H=7

L=1, W=2, H=3

Page 68: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Hello

Hello

As part of the Java Language Specification (the ‘rules’ for the Java Language), Strings have a special characteristic. It turns out that in some circumstance (BUT NOT ALL), you can use ‘==‘ to compare Strings, in addition to .equals(). Consider:

String strHello1 = “Hello”;String strHello2 = “Hello”;

We would expect these lines to produce thefollowing memory changes

In fact, it produces the following results in memory:

strHello1strHello2

HellostrHello1strHello2

Equality with References to Objects:Strings are special

Page 69: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Why are Strings treated differently?

Strings are sometimes a special case of equivalency in Java. When the compiler encounters the lines:

String strHello1 = “Hello”;String strHello2 = “Hello”;

the compiler is smart enough to know that the two Strings are identical. So, it decides it will save a few bytes of memory and point to the same location in memory. The same result would occur even if you wrote:

String strHello2 = “Hell” + “o”;

This means that for the above lines of code, equals() and ‘==‘ both work:

System.out.println (strHello1.equals(strHello2)); // trueSystem.out.println (strHello1 == strHello2); // also true,

Page 70: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Exception to the exception with StringBut this special case for ‘==‘ comparison of Strings DOES NOT ALWAYS WORK . . .

Consider: If one of the Strings were created with use of the ‘new’ keyword, the two Strings would no longer share memory. (That is, ‘==‘ would be false, but equals() would still be true, if the contents of the Strings are the same.)

So, there’s an exception to the exception for Strings when you don’t use the String exception to object instantiation. Confusing? Exceptionally so!

LESSON: DON’T USE THE EXCEPTION. Don’t compare Strings, or any Object, with ‘==‘, even if you think the exception will apply.

Page 71: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Debugging StrategiesDebugging StrategiesIncremental Programming:

The Idea: Find and repair bugs “in the small” before you have a program with several components. The hardest thing is finding the errors. So, find them as you create each class.

Thus, do not:• write your entire program, then• type in your entire program, then• attempt to test your entire program

Instead:• design your program at high level, focus on one class at a time,• for each class, write and test before going on to the next one.

Page 72: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Debugging StrategiesDebugging Strategies

Potential problems with state objects: State incorrectly modified by modifer methods. State incorrectly represented by accessor methods.

Need: A way to see the state of the object.

Means: public String toString ( )

• Create one “toString” method per class.

• Use it to put a reference to object directly in:

System.out.println ( );

Page 73: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

If have method for Class Box:

public String toString ( ) { String strReturn strReturn = new String(“Box: length = “ + iLength + “, Width = “ + iWidth + “height = “ + iHeight); return strReturn;

} // of toString

Then we can do:

System.out.println ( subwooferBox );

Example of using toString:

Page 74: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

25

Debugging StrategiesDebugging Strategies

• According to Java, you only need one main per program. . . not one per class.

• But Java doesn’t know how to program!

• To test/debug a class, create a main method for the class as part of the class . . .

• Include in “test mains” the:declaration of variablesthe invocation of methodsthe generation of output (e.g. using toString())

that will allow you to see what the class actually does!

Page 75: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Sumary so far• Strings and debugging

– Strings are objects• Concatenation with + operator• Lots of useful string manipulation methods in

java.lang.String– Strings are special:

• Don’t need to instantiate;

can initialize by assignment• Can usually compare with

==, but don’t rely on it– toString() and debugging main()

• Define a toString() method

for debugging each class

Page 76: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

• Thus far, data has been simple structures

• Java also allows collections of data:- as part of the API- in user defined classes

• Important collections include:- arrays (today)- vectors- linked lists- trees

(Note: In Java, Strings are not arrays or lists of characters)

CollectionsCollections

Page 77: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

ArraysArrays

Java array declaration:

<elementsType>[ ] <arrayIDer> = new <elementsType>[<size>];

e.g.: to declare an array of ten ints for storing numerical grades...

int[ ] iGradeArray = new int[10];

Array declaration error:

using parentheses, not brackets, e.g.,

int[ ] iGradeArray = new int(10);

The Idea:• Same concepts you know from Pseudocode• A few differences in implementation

Page 78: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Example:• declare iGradeArray of 10 ints• initialize all 10 values to 0

int[ ] iGradeArray = new int[10];int i; // when declaring and manipulating arrays, you may // use the single-letter IDers i, j, k for indices // due to convention (everybody knows what it is)

for (i=0; i < iGradeArray.length; i++) { iGradeArray[i] = 0; } // for loop

ArraysArrays

Great idea! if you change the array size, you need only change theinstantiation.

Page 79: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

ArraysArrays

Notes:• All arrays are objects, thus you must declare a reference, and instantiate it, and initialize it• Arrays know their own length• length is a field, not a method• Arrays are statically sized: you cannot change the length after declaration.

Page 80: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

More Notes:• Array indices begin at 0, not at 1• So, length is one greater than iMAX_INDEX• Thus, an error if you do:

int[ ] iGradeArray = new int[10];int i; for (i=1; i <= iGradeArray.length; i++){ iGradeArray[i] = 0;} // for loop

• Code above attempts to access elements 1..10• But... you have indices 0..9• So: it misses the 1st element (which is at index 0) it tries to go past 10th element

ArraysArrays

Page 81: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Example: represent a student who• keeps track of quiz and program grades.• can add a quiz grade and a program grade.

class JavaStudent { public static final int iMAX_NUM_QUIZ = 8; public static final int iMAX_NUM_PROG = 9;

int[ ] iQuizArray; int iQuizIndex = 0;

int[ ] iProgArray; int iProgIndex = 0;

ArraysArrays

continued

Page 82: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Arrayspublic JavaStudent( ) {// constructor to initialize elements to 0 iQuizArray =

new int[iMAX_NUM_QUIZ]; for (iQuizIndex=0; iQuizIndex <

iMAX_NUMQUIZ; iQuizIndex++)iQuizArray[iQuizIndex]=0;

iQuizIndex = 0;

iProgArray = new int[iMAX_NUM_PROG];

for (iProgIndex=0; iProgIndex < iMAX_NUM_PROG; iProgIndex++) iProgArray[iProgIndex]=0; iProgIndex = 0;} // constructor

Page 83: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

public void addProgGrade (int iNewProgGrade) { iProgArray[iProgIndex] = iNewProgGrade; iProgIndex++; } // of addProgGrade

public void addQuizGrade (int iNewQuizGrade) { iQuizArray[iQuizIndex] = iNewQuizGrade; iQuizIndex++; } // of addQuizGrade

} // of CS1502Student

Arrays

Page 84: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

ArraysPotential Errors: out of range indices:

• Compile time: bad int value known, e.g.,

iQuizArray[9] = iNewQuizGrade.

• Runtime: bad int value via variable, e.g., iQuizArray[iQuizIndex] = iNewQuizGrade;

Design issues: This example is legal Java, but is it good OO?

Page 85: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Example: represent a franchised cafeteria that has limits on: trays, flatware, seats.

class Cafeteria { int iSumTrays = 0; int iSumFlatware = 0; int iSumSeats = 0; public Cafeteria(int iSumTrays, int iSumFlatware, int iSumSeats) { setSumTrays( iSumTrays ); setSumFlatware( iSumFlatware ); setSumSeats( iSumSeats ); } // of constructor

/* We assume accessors, modifiers: getTrays( ), setTrays( ), etc.-- are implemented here*/

} // of Cafeteria

ArraysArrays

Page 86: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

public class Primes { public static void main (String arg[ ]) { int MAX = 100; boolean[ ] bPrime = new boolean[MAX]; bPrime[1] = false;

/* set all candidates to true */ for (int i=2; i< MAX; i++) bPrime[i] = true;

/* set to false all multiples of the counters */ for (int I = 2; I < MAX/2; i++) for (int j = 2; j < MAX/i; j++) bPrime[i* j]=false;

/* print results */ for (int i=1; i<MAX-1; i++) if (bPrime[i]) System.out.println (i + " is prime"); } // main} // class Primes

Note:

Here, the importantinformation is storedas the index value of

the array; we don’t place numbers in the

array itself.

Page 87: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

An array may be declared to be: an array of primitives, or an array of objects.

Arrays are objects, even if the array contains primitives.

(Array identifier references an object).

If an array of objects, then: the array IDer is a reference to the array each array element is a reference to an object of the class specified as elements

Instantiating the array object does not instantiate the various element objects to which it refers.

Element objects must be explicitly instantiated and initialized.

ArraysArrays

Page 88: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Then, the code segment:

Cafeteria cafeteria1 = new Cafeteria(10, 20, 30);Cafeteria cafeteria2;

produces:

iSumTrays = 10iSumFlatware = 20iSumSeats = 30

cafeteria1

cafeteria2

ArraysArrays

Page 89: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

and the code segment:

Cafeteria[ ] cafeteriaArray = new Cafeteria[5];

produces:cafeteriaArray

which could then be initialized:

int i;

for ( i = 0;

i < cafeteriaArray.length; i++)

cafteriaArray[i] =

new Caferia(10, 20, 30);

ArraysArrays

Page 90: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

giving:

cafeteriaArray

iSumTrays = 10iSumFlatware = 20iSumSeats = 30

iSumTrays = 10iSumFlatware = 20iSumSeats = 30

iSumTrays = 10iSumFlatware = 20iSumSeats = 30

iSumTrays = 10iSumFlatware = 20iSumSeats = 30

iSumTrays = 10iSumFlatware = 20iSumSeats = 30

iSumTrays = 10iSumFlatware = 20iSumSeats = 30cafeteria1

cafeteria27 objects

7 objectsin total

in total6 cafeteria

6 cafeteria

objects

objects

ArraysArrays

Page 91: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

but the code segment:

int i;for ( i = 0; i < cafeteriaArray.length; i++) { cafeteriaArray[i] = cafeteria1;} // of for loop initialization

produces:

cafeteriaArray

cafeteria1

1 cafeteria object...

1 cafeteria object...

2 objects in total

2 objects in total

ArraysArrays

iSumTrays = 10iSumFlatware = 20iSumSeats = 30

Page 92: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Arrays - Creation

• Declaration and instantiation: int[] myInts = new int[10];

myInts[0] =3;

• Static initialization:

int[] myInts =

{1,2,5,6,7,4,3,23,

4,4,3,3,5};

Page 93: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Multi-Dimensional Arrays

int [][] myTwoDimArray;

myTwoDimArray = new int[10][5];

• Quiz yourself: • Valid?

String[][] s;

s = new String[10][];

• Valid? s = new String[][10];

Page 94: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

String s[][] = {{"Static", "multidimensional", "initialization", "of"}, {"arrays", "requires",

"the", "use"}, {"of", "nested", "parens"} };

Static multidimensional initialization:

Page 95: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Static arrays of

multidimensional requires nested

initialization the parens

of use null

Results:• Note ‘null’ default

• Note ordering

s[2][1] --> “the”

Page 96: Lecture 2: Objects, References, Constructors, Scope, Wrappers, & Debugging Suggestions. Java for the Impatient

Summary of Arrays• Arrays

– All arrays are objects (you have to declare, instantiate, and initialize)

– Arrays are either arrays of primitive elements (e.g. int) or arrays of objects (really references to objects)

– Arrays are statically sized: you

can’t change length after

Use Array.length in for loops to avoid “off-by-one” errors– 2D arrays are arrays of arrays

• Don’t go yet, there’s one more slide….