Title: Objects, References, Constructors, Scope, Wrappers,
1Java for the Impatient
- Lecture 2
- Objects, References, Constructors, Scope,
Wrappers, Debugging Suggestions.
2Announcements
Web page http//www.cc.gatech.edu
/projects/gsams-java Please
respond to the surveys it helps all of us.
3Posted Questions
Declaration and use of counting variables outside
of loop structure? Yes safe for
interpreted language such as Java (with gc no
registers). Allows for common sense. Further
encourages consideration of variable creation
and scoping.
4Posted Questions
What else was wrong with if/else structure from
previous slides? As noted last week, use of
constants for grade codes (e.g., A 90) would
enable efficient maintenance of program.
5Posted Questions (contd)
Use of NTEmacs editor? Not covered herein.
Links http//www.xemacs.org http//www.cc.gate
ch.edu /classes/cs1502
/ntemacs/ides.html Ask about our lab materials
6Posted Questions (contd)
Improve size of font!
Hows this? Also, you might refer to printed
slides. Feedback mechanism?
7Lecture Topics
- 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
8Last 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 gt 0,
iNewLength lt 0) iLength
iNewLength // of setLength public int
getLength ( ) return (iLength) //
of getLength
Introduction to Programming, Lecture 3
9public void setWidth (int iNewWidth)
util.ASSERT (iNewWidth gt 0, iNewWidth lt 0)
iWidth iNewWidth // of setWidth
public int getWidth ( ) return
(iWidth) // of getWidth public void
setHeight (int iNewHeight)
util.ASSERT (iNewHeight gt 0,
iNewHeight lt 0) iHeight iNewHeight
// of setHeight
10 public int getHeight ( ) return
(iHeight) // of getHeight public int
getVolume ( ) return ( getLength( )
getWidth( ) getHeight( ) ) // of
getVolume // of class Box
11Declaring Objects
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.
Introduction to Programming, Lecture 3
12Declaring Objects
- Thus, 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
13Objects References
Box shoeBox
shoeBox
- To make the reference
- shoeBox be not null,
- it is necessary to
- instantiate it, e.g.,
- shoeBox new Box( )
Box Instance
shoeBox
14Objects References
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.
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.)
15Objects References
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 closer look
shoeBox
(a reference to an object of class Box)
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 its not technically
what happens with the heaps method space in the
Java Virtual Machine.)
16Objects References
Box shoeBox new Box() Box cdBox new
Box() Box present new Box()
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 ( )
cdBox
Each time we instantiate a Box, therefore, we get
a unique copy to work with. This is one of the
most powerful aspect of Object-Oriented
Programming!
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 ( )
present
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 (
) . . .
17What do we conclude from this?
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)
18References vs. Pointers
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.
19Objects and References
Distinguish between primitives and
objects. Assignment with Primitives Code
Memory
x
int x
int y
y
x
x 5
x5
y
y x
x5
y5
Introduction to Programming, Lecture 3
20Objects and References
Assignment with References to Objects
Code
Memory
Box box1 Box box2
box1 box2
L8, W5, H7
box1 box2
box1 new Box(8, 5, 7)
box2 box1
L8, W5, H7
21Objects and References
box1box2
box1 new Box(3, 9, 2)
L3, W9, H2
L8, W5, H7
box1 box2 // Old reference lost!
box1box2
L3, W9, H2
L8, W5, H7
22Calling Methods
- Given what weve 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
23Calling Methods
- class WallstreetJitters
- public void panicSell ( )
- FedResChair greenspan
- new FedResChair()
- if (greenspan.raisesInterest())
-
- buyOnMargin()
- else
-
- sellAllStock()
-
- // of panicSell
- // of WallstreetJitters
FORMAT ltobject referencegt.ltmethod namegt
If the method is NOT inside the class where
method declared, then the object must be
specified.
The class FedResChair must have this method!
These methods must appear in WallstreetJitters
class!
24Questions?
- 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
25Constructors
MotivationWe need a means of initializing the
attributes of a new object (or instance) when
it is created.
MeansConstructor methods that are invoked
automatically upon instantiation (creation) of
new object.
Example public Box (int iNewLength, int
iNewWidth, int iNewHeight) setLength
(iNewLength) setWidth (iNewWidth)
setHeight (iNewHeight) // of constructor
26Constructors
Note 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.setHeig
ht(82)
27Constructors
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.
Given public String ( ) public String
(String value)
28class 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 the constructors call the modifiers
29Java Constructors
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.
30Java Constructors
Default constructors If you dont 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.
31Java Constructors
Constructors CANNOT have return values Do
NOT do this public int Person ( )
. . . // whatever
code // of constructor public
void Person ( ) . . .
// whatever code // of constructor
A return value (including void) means that the
method is NOT a constructor, and it wont be
auto-invoked.
32Creating Instances of Classes
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)
33Instance vs. Class Declarations
- A distinction that applies to both variables and
methods - An instance ltvariable or methodgt is one that
belongs to each object of a class. - A class ltvariable or methodgt 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.
34Instance vs. Class Variables
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!
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
35Instance vs. Class Variables
class Human String strName static int
iPopulation 0 public Human (String
strName) this.strName strName
iPopulation // of constructor // of
Human
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.
one change
As we know, this declares a strName String for
each instance. Thus, each Human will have its
own name.
36Instance 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.
37Instance vs. Class Variables
Declares a different-but-identical constantfor
each instance of the class. Wasteful with zero
benefit.
Constants Revisited class
ConstantExample final int
iMAXSIZE 10 // of ConstantExample
class ConstantExample
static final int iMAXSIZE 10 // of
ConstantExample
Declares a single constant for use by all
instances of the class.
38Questions?
- 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
39Objects and References
Assignment 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).
40Objects and References
Two references to a single area of memory
Assignment operator
Creates a new area in memory so each named
reference points to its own object
clone()
41Objects and References
Assignment with References to Objects Given
this
str1 str2
howdy
doody
The statement str1 str2 would give
Two references to one object
str1str2
howdy
doody
But str1 str2.clone() would give
str1 str2
Two distinct areas of memory
doody
doody
42Objects and References
Equality with Primitives
int iBraves int iPhillies iBraves
11 iPhillies 3 System.out.println(iBraves
11) // prints true System.out.println
(iPhillies 3) // prints
true System.out.println(iBraves iPhillies)
// prints false iBraves iVikings System.out.
println(iBraves 3) // prints
true System.out.println(iPhillies 3) //
prints true System.out.println(iBraves
iPhillies)
// prints true System.out.pri
ntln(iBraves gt iPhillies)
//
prints false (!)
iBraves
iPhillies
11
3
iBraves
iPhillies
3
3
43Objects and References
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.
For primitives
For objects
44Objects and References
Equality 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?
45Objects and References
Box box1 new Box(8, 5, 7) Box box2 new
Box(8, 5, 7)
.equals( ) compares if the objects have the same
content!
compares if these references point to the
same place in memory!
46Objects and References
The equals( ) method is therefore useful in
comparing objects. Heres 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
Note we must decide what constitutes equivalency
Casting (covered later)
47Objects and References
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 (Its 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.
48Objects and References
As 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 wasnt 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.
49Java Parameters
- Pseudocode has 3 basic kinds of parameters
- in
- out
- in/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.
50Java Parameters
- For 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.
51Java Parameters
Given 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(i
This, , , iThat) // line c swap (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 )
52Java Parameters
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.pri
ntln(strTemp) // line c test(strTemp) Sy
stem.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 )
53Java Parameters
- 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 objects
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).
54Java Parameters
Java parameter variables are (as youd 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.
55Scope
- Local 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
56Preventing Identifier Ambiguity
We want to refer to the instance variable
strName inside the method, but this code fails!
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?
WRONG!
57Preventing Identifier Ambiguity
- 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
58Summary 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 method When ids are ambiguous, the most local
one takes priority
59Strings vis-a-vis Objects
Every String is an instance of Javas 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 . . .
60Strings vis-a-vis Objects
Assignment w/References to Strings/Objects
Code
Memory
String str1 Box box1
str1 box1
str1 Hello World box1 iLn, iWd, iHt
str1box1
Hello World
ERROR must use new new and call constructor
61Strings vis-a-vis Objects
str1box1
Hello World
str1 Hello World box1 new Box(iLn, iWd,
iHt)
iLn, iWd, iHt
str2
str2 new String() str2 Glib Folksies
default
?default?
str2
Glib Folksies
Strings are immutable
62Strings vis-a-vis Objects
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 Java treats standard objects. With
standard objects, you must explicitly
instantiate (via new), and initialize (via a
constructor).
63String Stuff
1. 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.)
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
64Strings Stuff -- Examples
String strExample Hello
char c strExample.charAt(1) // c gets
e String strBritishHowdy
strExample.substring(1)
strBritishHowdy ---gt ello String
strLectureRoomTemperature
strExample.substring(0, 4)
strLectureRoomTemperature --gt Hell
65Strings vis-a-vis Objects
Also . . . One cannot change contents of a
String object. (We say Strings are
immutable.) You may think you are modifying a
String. But, what happens in 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
String str1 Hello World str1
str1.substring(4)
Hello World
str1
str1
Hello World
o World
66Objects and References The 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 weve covered so far - 1. When comparing primitives (int, float,
etc.), use - 2. When comparing objects (String, or any class
you create), use the equals() method. - 3. When you create a class that
- serves as a data type or record,
- remember to include an
- equals() method.
- In the slides ahead we will note some
- rare exceptions where the
- comparison will work for objects.
67Objects 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(box
1 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
L1, W2, H3
L8, W5, H7
68Equality with References to Objects Strings are
special
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
the following memory changes
Hello
strHello1 strHello2
Hello
In fact, it produces the following results in
memory
strHello1 strHello2
Hello
69Why 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.pr
intln (strHello1.equals(strHello2)) //
true System.out.println (strHello1
strHello2) // also true,
70Exception to the exception with String
But 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, theres an
exception to the exception for Strings when you
dont use the String exception to object
instantiation. Confusing? Exceptionally
so! LESSON DONT USE THE EXCEPTION. Dont
compare Strings, or any Object, with , even
if you think the exception will apply.
71Debugging Strategies
- Incremental 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.
72Debugging 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 ( )
73Example of using toString
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 )
74Debugging Strategies
- According to Java, you only need one main per
program. . . not one per class. - But Java doesnt 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 variables
- the invocation of methods
- the generation of output
- (e.g. using toString())
- that will allow you to see what
- the class actually does!
25
75Sumary so far
- Strings and debugging
- Strings are objects
- Concatenation with operator
- Lots of useful string manipulation methods in
java.lang.String - Strings are special
- Dont need to instantiate
- can initialize by assignment
- Can usually compare with
- , but dont rely on it
- toString() and debugging main()
- Define a toString() method
- for debugging each class
76Collections
- 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)
77Arrays
- The Idea
- Same concepts you know from Pseudocode
- A few differences in implementation
Java array declaration ltelementsTypegt
ltarrayIDergt
new ltelementsTypegtltsizegt e.g. to declare
an array of ten ints for storing numerical
grades... int iGradeArray new int10
Array declaration error using parentheses, not
brackets, e.g., int iGradeArray new
int(10)
78Arrays
- Example
- declare iGradeArray of 10 ints
- initialize all 10 values to 0
int iGradeArray new int10 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 (i0 i lt
iGradeArray.length i) iGradeArrayi
0 // for loop
Great idea! if you change the array size, you
need only change the instantiation.
79Arrays
- 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.
80Arrays
- 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 int10 int i for
(i1 i lt iGradeArray.length i)
iGradeArrayi 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
81Arrays
- 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
continued
82Arrays
public JavaStudent( ) // constructor to
initialize elements to 0 iQuizArray new
intiMAX_NUM_QUIZ for (iQuizIndex0
iQuizIndex lt iMAX_NUMQUIZ iQuizIndex) iQuizAr
rayiQuizIndex0 iQuizIndex 0
iProgArray new intiMAX_NUM_PROG for
(iProgIndex0 iProgIndex lt iMAX_NUM_PROG
iProgIndex) iProgArrayiProgIndex0
iProgIndex 0 // constructor
83Arrays
public void addProgGrade (int iNewProgGrade)
iProgArrayiProgIndex iNewProgGrade
iProgIndex // of addProgGrade
public void addQuizGrade (int iNewQuizGrade)
iQuizArrayiQuizIndex iNewQuizGrade
iQuizIndex // of addQuizGrade // of
CS1502Student
84Arrays
- Potential Errors out of range indices
- Compile time bad int value known, e.g.,
- iQuizArray9 iNewQuizGrade.
- Runtime bad int value via variable, e.g.,
- iQuizArrayiQuizIndex
- iNewQuizGrade
- Design issues
- This example is legal Java,
- but is it good OO?
85Arrays
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
86public class Primes public static void main
(String arg ) int MAX 100
boolean bPrime new booleanMAX
bPrime1 false / set all candidates
to true / for (int i2 ilt MAX i)
bPrimei true / set to false all
multiples of the counters / for (int I
2 I lt MAX/2 i) for (int j 2 j lt
MAX/i j) bPrimei jfalse
/ print results / for (int i1 iltMAX-1
i) if (bPrimei)
System.out.println (i " is prime") //
main // class Primes
Note Here, the important information is
stored as the index value of the array we dont
place numbers in the array itself.
87Arrays
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.
88Arrays
Then, the code segment
Cafeteria cafeteria1 new Cafeteria(10, 20,
30) Cafeteria cafeteria2
produces
iSumTrays 10 iSumFlatware 20 iSumSeats
30
cafeteria1
cafeteria2
89Arrays
and the code segment
Cafeteria cafeteriaArray new Cafeteria5
produces
cafeteriaArray
which could then be initialized
int i for ( i 0 i lt
cafeteriaArray.length i) cafteriaArrayi
new Caferia(10, 20, 30)
90Arrays
giving
iSumTrays 10 iSumFlatware 20 iSumSeats
30
cafeteria1
6 cafeteria objects
7 objects in total
cafeteriaArray
iSumTrays 10 iSumFlatware 20 iSumSeats
30
iSumTrays 10 iSumFlatware 20 iSumSeats
30
iSumTrays 10 iSumFlatware 20 iSumSeats
30
iSumTrays 10 iSumFlatware 20 iSumSeats
30
iSumTrays 10 iSumFlatware 20 iSumSeats
30
91Arrays
but the code segment
1 cafeteria object... 2 objects in total
int i for ( i 0 i lt cafeteriaArray.length
i) cafeteriaArrayi cafeteria1 // of
for loop initialization
produces
cafeteria1
iSumTrays 10 iSumFlatware 20 iSumSeats
30
92Arrays - Creation
- Declaration and instantiation
- int myInts new int10
- myInts0 3
- Static initialization
- int myInts
- 1,2,5,6,7,4,3,23,
- 4,4,3,3,5
93Multi-Dimensional Arrays
- int myTwoDimArray
- myTwoDimArray new int105
- Quiz yourself
- Valid?
- String s
- s new String10
-
- Valid?
- s new String10
94Static multidimensional initialization
- String s "Static", "multidimensional",
"initialization", "of", "arrays", "requires",
"the", "use", "of", "nested", "parens"
95 Static arrays of multidimensional
requires nested initialization
the parens of use null
- Results
- Note null default
- Note ordering
- s21 --gt the
96Summary 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
- cant change length after
- Use Array.length in for loops
- to avoid off-by-one errors
- 2D arrays are arrays of arrays
- Dont go yet, theres one
- more slide.