GSAMS’
Undistinguished
Lecture Series
presents . . .
Java for the Impatient
WHO
@
Russ Shackelford, B.A., M.A., M.S.,
Ed.S., Ph.D.
David Dagon, B.S., J.D., etc.
[email protected]
[email protected]
WHAT
Covers essential Java syntax
and debugging techniques
Presumes familiarity
with computer, and
an IDE or text editor
David Dagon:
Georgia Tech’s introductory
computing course has the students
use NTEmacs with JDE to edit their
code. You can get a copy of this
distribution at:
http://www.cc.gatech.edu/classes/cs1502
Look for the links on “Help with IDEs”
A Note on Noise
• Some noise is good
• We must share the medium, and
should be aware of others.
• However, please
feel free to
ask questions
What is Java?
"A simple, objectoriented, distributed,
interpreted, robust,
secure, architecture
neutral, portable,
high-performance,
multithreaded, and
dynamic language”
-- Sun
Sounds like
marketing;
let’s take a
closer look . . .
David Dagon:
FYI. The next set of slides
give a brief explanation of
each of these terms. Some of
the slides introduce some
complicated subjects; future
sets of slides will cover them
in greater detail.
“… object oriented …”
Java is an “object oriented” (or “OO”) language.
• It is possible (but seldom desirable) to write nonobject oriented Java code (so-called “hybrid OO”).
• In an OO language, classes are used to
encapsulate data (state) and behavior.
• Instances of a class are then
used to manipulate data and
drive the program.
• Classes are arranged in an
hierarchy, or package structure.
“… object oriented, …”
Example:
A “Stack” is a class found in the package
java.util. We create an instance of the class
Stack using the keyword new thus:
import java.util.*;
Stack c = new Stack();
c.push(“3”);
java.util.Stack x = new Stack();
This differs from procedural (e.g., C)
and functional languages (e.g., Lisp)
where other data structures would
be used to model the Stack. More on
classes in later slides . . .
David Dagon:
It’s difficult to come up with a simple example
of an object. One might use java.lang.String;
however, there are some exceptions to String
creation built into Java. One could also use
the java.lang.Integer class; however, this
presumes some knowledge of wrapper
classes.
Note also that I’ve called the Stack in this
example “c”, instead of “myStack” or
something similar. It’s very common to use
the ‘my-’ prefix in object creation; however,
those not used to OO language might find it
confusing. To emphasize that the Stack
instance is merely an object, we use the
familiar variable ‘c’. Of course, we could have
called the Stack “foo”.
“… distributed, …”
Java is also a distributed language.
It was built with networking in mind
Fully supports IPv4, with structures to support
IPv6.
Includes support for “Applets”:
small programs embedded in
HTML documents.
See:
java.net package
RMI/CORBA
David Dagon: Java provides
convenient access to the OSI
Network layer. Other APIs
allow one to access even
lower layers.
“… interpreted, …”
Java is an interpreted language, meaning that
each instruction is translated into machine code
at the time of execution, not during compilation.
This allows for platform neutrality:
“WORA”
This allows one to rewrite and
change a program while it
is running.
Penalty: speed
“… robust, …”
Java is simple--no pointers/stack concerns (for
the most part)
In-bound checking at runtime of array pointers-no memory corruption and cryptic error
messages.
Exception handling: try/catch
/finally series allows for
simplified error recovery
Strongly typed language:
many errors caught during
compilation.
“… secure, …”
Byte-code verification on loading (not just
compilation).
Applet code runs in 'sandbox', with significant
restrictions
Security is enforced by the
SecurityManager class
Work-arounds for applet
security restrictions include
digitally signing code, and
Servlets
Evaluation of Java
• Strengths of Java:
–
–
–
–
–
A real language, in demand in industry
Portability
Comparatively easy to learn
Difficult to destroy a machine with it ;-)
Advanced built-in GUI/Graphics features
• Weaknesses of Java:
– Slow: interpreted and OO
– GUI/Graphics via “Least
Common Denominator”
approach (due to platform
independence)
– Awkward/annoying syntax
Structure of Java Programs
• Applications (“normal” computer
programs):
– Each program consists of multiple files.
– Each file contains a class.
– First method (module) called is:
public static void main(String[ ] argv)
– The main method controls
program flow (but OO
orientation means that it
starts a process that
features decentralized
control).
Structure of Java Programs
• Applets (transportable over WWW):
– Similar to applications, but...
– First method is:
public void init( )
– Remainder of applet is a series of
handlers that respond to events (e.g.,
user actions).
– Program is executed by
Java interpreter running
in Web browser or
applet viewer.
Sample Program (in a file
called “HelloWorld.java”)
public class HelloWorld
{
public static void main(String argv[])
{
System.out.println(“Hello World!”);
}
}
Basic Syntax
All java programs contain (within one or more*
classes):
public static void main (String a[ ])
{ ... }
The Java interpreter runs until
the main() returns, a System
or Runtime exit is called,
a fatal error occurs, or until
the end of
main is found.
David Dagon: The following
slide is the traditional
HelloWorld program. Note
that white space is irrelevant.
Also note that the naming of
local variables is arbitrary
(compare a[ ] to arg[ ]).
GoodBye World
import java.lang.Runtime; /* not necessary */
class GoodByeWorld {
public static void main (String arg[]) {
Runtime.getRuntime().traceInstructions(true);
Runtime.getRuntime().traceMethodCalls(true);
System.out.println (”Here’s some stats:");
System.out.println
(Runtime.getRuntime().totalMemory() +
" total memory\n” +
Runtime.getRuntime().freeMemory()
+ " available");
if (true) return; /* 1 */
System.exit(0);
/* 2 terminates */
Runtime.getRuntime().exit(0);
/* 3 terminates only if
the thread is running */
} /* 4 --end of main*/
}//test
Vocabulary
• Structured Programming:
– A programming paradigm in which the actions
(or verbs, or procedures) are emphasized.
• OO Programming:
– A programming paradigm in which the actors (or
nouns, or objects) and their interaction is
emphasized.
• Byte Compiler:
– A compiler which translates
human-readable source code
into byte code (transportable
to various virtual machines)
instead of object code written
for a specific kind of machine.
Vocabulary (cont’d)
• Byte Interpreter:
– An interpreter which translates byte code into
object code for a particular kind of machine and
executes them on that machine.
• Byte Code:
– An instruction for a virtual machine.
• Java Virtual Machine (JVM):
– The virtual machine (software)
for which all Java programs
are compiled. A byte code
interpreter is required to
translate from the JVM byte
code instructions into to
instructions for a given
actual machine.
Java’s Popularity
• Keys to Java’s Popularity:
– An OO language that’s relatively
simple.
– Virtual Machine approach,
allowing transportability to various
different kinds of computers
(operating systems).
– Presence of JVM as
part of Web browsers,
encouraging movement
of Java programs
over the Web.
Primitives
Java is not a purely OO language,
and supports several primitive
data types, including:
Primitive Type
boolean
char
byte
short
int
long
float
double
void
Default Value
false
'\u0000' (null)
(byte) 0
(short) 0
0
0L
0f
0d
N/A
David Dagon: According to
the Java Language
Specification, void is a
primitive. But introducing void
to students might be
confusing. We include it here
to be complete; in teaching,
you might omit this 9th
primitive
Variable Declarations
• Java:
–
<datatype>
<identifier>;
• or (optional initialization at
declaration)
–
<data type> <identifier> = <init
value>;
int x;
x = 3;
int y = 5;
Naming Conventions
• Begin variable identifiers with
abbreviation of their type:
–
–
–
–
–
i for int (integer)
f for float
b for boolean
ch for char
str for String
Examples
•
•
•
•
•
•
•
•
•
•
•
int iCounter;
int iNumStudents = 583;
float fGPA;
float fBatAvg = .406;
char chGender;
char chGender = ‘f’;
boolean bSafe;
boolean bEmpty = true;
String strPersonName
= “Fred”;
String strStreetName;
Operators
• Assignment: =
• Arithmetic: +, -, *, /, % (mod)
int iNumLect = 2;
int iNumStudents = 583;
int iStudentsPerLect;
iStudentsPerLect = iNumStudents / iNumLect;
// gives 291 due to integer division
int iNumQualPoints = 30;
int iNumCreditHours = 8;
float fGPA;
fGPA =
iNumQualPoints / iNumCreditHours;
// gives 3.0 due to integer division
iVar = iVar * flVar
// gives compile-time error
Shorthand Operators
• iCounter = iCounter
iCounter++;
• iCounter = iCounter
iCounter--;
• iCounter = iCounter
iCounter+=2;
• iCounter = iCounter
iCounter*=5;
• latter 2 examples:
+ 1;
OR
- 1;
OR
+ 2;
OR
* 5;
OR
– it’s “op” then “equals”
(e.g., +=2), not “equals”
then “op” (e.g., isn’t =+2)
Some Comments on Comments
1. C-style comments with /* */; no nesting
2. C++ style comments beginning //
3. A unique "doc comment" starting with /** ...*/
Fun with comments:
/*/
/*
worthless
// */
///////////////////
Never closed
Good for blocks
/* ========= */
Javadoc
/**
* <PRE>
* getName(int i) - returns the name at a
* specified array location
* </PRE>
* @param int i - the index of the array to
*
be retrieved
* @return String strName - the name
* @see Employees#isEmployed() - called to
*
verify employment
*/
public String getName (int i)
if (myEmpl.isEmployed())
return myArray[i];
else return "Nada";
} // getName(int)
{
David Dagon: Javadoc can
generate an API listing of your
code
Javadoc (Cont’d)
• You may include HTML tags (but avoid structuring tags,
like <H1>, etc.)
• Javadoc comments should immediately preceed the
declaration of the class, field or method. The first
sentence should be a summary. Use the special javadoc
tags--@. When '@' tags are used, the parsing continues
until the doc compiler encounters the next '@' tag.
@ see <class name>
@ see <full-class name>
@ see<full-class
name#method.name>
David Dagon: The
@ version
@deprecated tag interacts with
@author
@param
the compiler to turn off
@return
@exception
warnings.
@deprecated
@since
@serial
// jdk 1.1
// jdk 1.1
// jdk 1.2
Constants
• Valid:
– public final <type> <IDer> = <value>;
• Preferred:
– public final static <type> <IDer> = <value>;
– public final static int
–
iMIN_PASSING = 60;
– public final static
float fPI = 3.14159;
• Details on “why this
syntax” to come soon...
Printing to Screen
• Various techniques:
–
–
–
–
System.out.println(<arguments>);
System.out.println( ); // prints blank line
System.out.println(5); // prints 5
System.out.println(“Hello World”);
// prints Hello World
– “println” vs. “print” in Java:
• println includes “carriage
return” at end, next print or
println on new line
• print causes next print or
println to begin at next
location on same line
Printing (cont’d)
• When starting Java, there are at
least three streams created for you:
System.in
System.out
System.err
// for getting input
// for output
// for bad news output
• These are InputStream and
PrintStream objects
•
Note: For Win95/NT System.out is
"almost" identical to System.err the both display to the screen
(the one exception is when using
DOS redirect, >, where System.out
is redirected, while System.err is
still put to the screen )
Printing (cont’d)
System.out.println
("This line is printed out")
System.err.println
("This is the error stream's output");
These are both instances of the PrintStream
class.
There are other methods you might find
useful in these classes:
System.out.flush();
System.out.write(int);
System.out.write(byte[] buf,
int offset, int length);
Decision Statements
• Java:
if (condition)
single statement;
else
single statement;
• or:
if (condition)
{
statements;
}
else
{
statements;
}
• Pseudocode:
if (condition) then
statements
else
other statements
endif
Conditional Assignment
boolean b;
int iCount;
<boolean> ? <true condition>
: <false condition>
b = checkCompletion();
iCount = (b) ? 3 : 1;
Must resolve
to boolean
If true . . .
. . . if false
Examples
• Pseudocode:
test_grade isofftype Num
...
is_passing isoftype
Boolean
is_passing <- TRUE
if (test_grade < 60) then
is_passing <- FALSE
endif
print (is_passing)
• Java: what happens
here?
boolean bPassing = true;
int
iTestGrade;
...
if (iTestGrade < 70)
bPassing = false;
System.out.println
(bPassing);
Boolean and
Relational Operators
• Boolean:
Pseudocode:
AND
OR
NOT
AND
OR
NOT
• Relational
equal to
not equal to
less than
less than or equal to
greater than
greater than
or equal to
=
<>
<
<=
>
>=
==
!=
<
<=
>
>=
Java:
&&
||
!
Errors
• Compile-time errors:
– Syntax errors: illegal language statements
– Certain kinds of semantic errors.
e.g., type mismatch (assign a Character value to
Boolean var)
• Run-time errors:
– Certain kinds of semantic errors.
e.g., try to access non-existent
dynamic data (dereference a
nil/null pointer)
– Logic errors: legal program
that produces wrong behavior
Debugging Strategies
• Compile-time errors:
– The compiler will yell at you about them.
• BUT . . . industry research shows . . .
– It is a time-waster to:
• code sloppy
• use the compiler to find your mistakes
• It is faster to:
– check the “annoying details”
of your code to catch them
BEFORE compilation.
• Lesson: don’t become a
compiler junkie!
Debugging Strategies
• Run-time errors:
– Programming environment provides tools for
tracing values as code executes.
– But: the most basic tools are independent of the
programming environment:
• 1. Code tracing: use your eyes and mind!
• 2. Use print statements:
insert statments that tell you
what key values are at given
points in your program.
• 3. Use DEBUG flags:
build in print statements
in a way that lets you turn
them on and off.
The “DEBUG” Flag Idea
• In Pseudocode:
// in the main
DEBUG is TRUE // or FALSE
// inside of procedure This_Proc . . .
if DEBUG then
print (“am entering proc This_Proc”)
print (“this_param: “, this_param:)
print (“that_param: “, that_param:)
endif
// code goes here
if DEBUG then
print (“am leaving proc This_Proc”)
print (“this_param: “, this_param:)
print (“that_param: “, that_param:)
endif
The “DEBUG” Flag Idea
• In Java:
public static final boolean DEBUG = true;
…
public void myMethod()
{
if (DEBUG)
System.out.println
(“Entering myMethod()”);
…
if (DEBUG)
System.out.println
(“Leaving myMethod()”);
}
Java File Names
Source code files must have the ".java"
extension. The file name should match the
class name. This naming convention is
enforced by most reasonable compilers.
Thus, an improperly named java file, saved
as "myTest.java":
class test { ... }
Compiled byte code has the
".class" extension.
Java File Structure
Java Files:
1. Consist of the optional package statement,
2. followed by any necessary import
statements
3. followed by the class name,
4. followed by any inheritance
and interface declarations.
5.
Note: if the file defines more than one
class or interface, only one can be declared
public, and the source file name must match
the public class name.
Thus:
An Average Java File
package edu.gatech.cc.dagon.gsams-java;
import java.util.*;
import edu.gatech.cc.dagon.gsams-java.hashtable.*;
import netscape.javascript.JSObject;
import netscape.javascript.JSException;
public class SplayTree implements TreeType, TreeConstants
{ ...
}// SplayTree
Note the globally unique
package name. Without a
package specification,
the code becomes part of an
unnamed default package in
the current directory.
Import Statements
Import statements Come in three flavors:
import package.class;
import package.*;
import java.lang.*;
// 1
// 2
// 3 (Implicit)
What it does: provides the Java interpreter with a
reference to other classes necessary
for the compilation of the
present .java file
What it does NOT: actually
"import" or ”#include" the
code. There’s no overhead
or object bloat.
Why No #include statements?
Java maps fully qualified class names to a
directory path, and therefore does not need an
#include, #ifdef, etc. (and no preprocessor as well)
Thus:
java.awt.TextField
is mapped to:
java/awt/TextField
and dynamically loaded,
as needed.
David Dagon: This explains the
mystery behind the error message
reported when one attempts to run a
file with the “.class” extension passed
into the java VM:
java FooBar.class
Exception in thread "main"
java.lang.NoClassDefFoundError:
FooBar/class
Here, the VM looks for a file “FooBar in
a folder called “class”
Also, some might argue that javadoc
and doclets are types of preprocessors.
Methods, Control
Structures and Data
Structures
Java Methods
There exists a single construct, the method, for both
procedures and functions:
• when a procedure is called for, specify
the return type “void” before method name
public void printHelloWorld( )
{
System.out.println(“Hello World!”);
} // of printHelloWorld
•Note: All methods must have parentheses
for parameters . . . even if no parameters!
Java Methods
Single construct for both procedures and functions:
• when a function is called for, specify the
appropriate return type before method name
public float average (float fNum1,
float fNum2, float fNum3)
{
float fReturnVal;
fReturnVal =
(fNum1 + fNum2 + fNum3)/ 3;
return (fReturnVal);
} // of average
Writing Methods: A Larger Look
A Java requirement:
--All methods belong to an object (or class).
--Name of object (or class) must be
unambiguous when method called.
--To run a program, there must be a class
(whose name is the name-of-the-program),
containing a special method called main:
visible
to all
nothing
returned
public static void main (String[ ] argv)
a class
method,
not an
instance
method
Method name
for command
line parameters
Multiple Selections via switch
Use if construct for one selection.
Use if/else construct for double selection.
Use switch construct for multiple selection.
(e.g., situations appropriate for if-elseif-elseif-else)
Note:
• Useful when making a selection
among multiple values of the
same variable.
• Not useful when selecting
among values of different variables.
Multiple Selections via switch--Notes
• The switch statement can only be used with
the following types:
int, char, short & byte
(You can cast floats, doubles, etc.)
• The case values must all be of the same type.
• The case values must all be
FINAL constants.
Multiple Selections via switch
switch (chGrade) {
case ‘A’: case ‘a’:
iCountOfAGrades++;
break;
case ‘B’: case ‘b’:
iCountOfBGrades++;
same
break;
case ‘C’: case ‘c’:
iCountOfCGrades++;
break;
case ‘D’: case ‘d’:
iCountOfDGrades++;
break;
case ‘F’: case ‘f’:
iCountOfFGrades++;
break;
default:
System.out.println(“Invalid grade”);
break;
}
If (chGrade==‘A’ || chGrade==‘a’)
iCountOfAGrades++;
else if (chGrade==‘B’ || chGrade==‘b’)
iCountOfBGrades++;
else if (chGrade==‘C’ || chGrade==‘c’)
iCountOfCGrades++;
else if (chGrade==‘D’ || chGrade==‘d’)
iCountOfDGrades++;
else if (chGrade==‘F’ || chGrade==‘f’)
iCountOfFGrades++;
else
System.out.println
(“Invalid grade”);
(assume these variables
exist and have value)
Multiple Selections via switch
Note the “optional” default case at the end of the switch statement.
It is optional only in terms of syntax.
switch (iNumber) {
case 1:
System.out.println (“One”);
break;
case 2:
System.out.println (“Two”);
break;
case 3:
System.out.println (“Three”);
break;
default:
System.out.println(“Not 1, 2, or 3”);
} // switch
In practice you should always include a ‘default’
case statement.
E.g., 1989 AT&T phone system crash
This would
work without
the default, but
would be
poor
technique
Java Basics: Iteration Constructs
• In Pseudocode, we had a single iteration
construct, flexible enough to be used in all iteration
contexts.
• Java, like most programming languages does not
provide a single flexible construct.
• Instead, Java offers three special case loop
constructs, each good for a particular context.
• Do not get accustomed to only one
of them and try to use it for
all situations.
Java Iteration Constructs: “For Loops”
Java syntax:
for (<initialization>; <continue if>;<increment>)
Pseudocode:
i isoftype Num
i <- 0
loop
exitif (i =10)
<some
statements>
i <- i + 1
endloop
Java example:
int i;
for (i=0; i<10; i++)
{
<some
statements>
}
For Loops
int count;
for (count = 0; count < 10; count ++)
for ( ; count < 10; count ++)
for (; count++<10;)
for (; ++count<10;)
for (int count =10; count -- > 0;)
for ( ; ; ) // infinite
for (count = 0; count < 10 &&
bNotDoneYet; count ++, otherCount--)
for (count = 0; count < 10;
printCount(count++); )
Java Iteration Constructs: “For Loops”
Common Problems with For Loops
include:
for (i=0; i<N; i++);
{…}
--Spins on ending semicolon; code in
braces executed once!
for (int i=0; i<N; i++){…}
--variable declared inside for
loop signature; poor style
--the variable may be needed
outside the for loop structure
Java Iteration Constructs: “Do While Loops”
Pseudocode:
loop
statement 1
...
statement N
exitif
(NOT(condition))
endloop
Java example:
do {
statement 1;
...
statement N;
} while (condition);
Java Iteration Constructs: “While Loops”
Pseudocode:
loop
<get the next value>
exitif (NOT(condition))...
<process the value>
endloop
Java example:
<get the first value>
while (condition) {
<process the
current value>
<get the next value>
}
Java Iteration Constructs: “While Loops”
When repeating steps, people naturally want to
follow the pattern:
get a value, then process that value
The while loop construct calls for the unnatural
pattern:
obtain the first loop control value before
entering the loop itself;
then, within the loop body,
first do the process steps,
then do the get next steps
Java Iteration Constructs: When to Use
--The term “control variable” refers
to the variable whose value is tested
to determine if the loop should
continue for another iteration or halt.
--For example, variable thisVar,
below:
while (thisVar < = SOME_CONSTANT)
--To determine which loop construct
is appropriate for a given situation,
ask yourself “where does the control
variable’s value come from?”
ASK:
Is it simply a count of the number
of iterations?
Is it a value that the loop itself
must compute?
Is it a value that already exists
somewhere, and the loop only
obtains it from elsewhere?
Java Iteration Constructs: When to Use
The for loop: used when the control variable is a simple
count of the number of iterations,
e.g.: “create a loop that reads and processes
the next 100 numbers.”
The while loop: used when the control variable has a value
that already exists and is simply obtained by the loop.
e.g.: “create a loop that reads in numbers and
processes them until it reads in a 100.”
The do-while loop: used when the control
variable’s value must be calculated
by the loop itself.
e.g.: “create a loop that reads in numbers
until their sum is greater than 100.”
Java Iteration Constructs: Review
Which loop construct would you use if...
You need to perform a series of steps
exactly N times?
You need to traverse a linked list of unknown
size, and stop when you find a certain value?
You need to perform a series of
steps at least once, and continue
performing these steps for an
unknown number of times
Debugging Tools/Strategies: The Assert Statement
CS1502 has created a general purpose utility class to assist you in
programming. (See the class web page, and labs.) One useful method is
ASSERT(), which can be used to validate assumptions and conditions.
Precondition: statement that must be true
before the method can begin execution.
Postcondition: statement that must be true
after the method has executed.
Usage:
util.ASSERT(iDenominator!=0,
“Can’t divide by zero!”);
iFraction =
iNumerator/iDenominator;
Writing Methods--Flawed Example
public char letterGrade (int iGrade) {
util.ASSERT(iGrade >= 0 && iGrade <=100,
“iGrade param has invalid value.”);
What’s wrong
if (iGrade >= 90)
return (“A”);
with this?
if (iGrade >= 80 || iGrade < 90)
return (“B”);
if (iGrade >= 70 || iGrade < 80)
--Error: returns a String,
return (“C”);
not a char!
if (iGrade >= 60 || iGrade < 70)
return (“D”);
if (iGrade <= 60)
return (“F”);
} // of letterGrade
--Style: use if/else chain to avoid
unintended execution of code
--Style: multiple returns are to
be avoided, if possible
Writing Methods--Repaired Example
public char letterGrade (int iGrade)
{
char chReturnValue = ‘I’;
util.ASSERT(iGrade >= 0 && iGrade <=100,
“iGrade param has invalid value.”);
if (iGrade >= 90)
chReturnValue = ‘A’;
else if (iGrade >= 80 && iGrade < 90)
chReturnValue = ‘B’;
else if (iGrade >= 70 && iGrade < 80)
chReturnValue = ‘C’;
else if (iGrade >= 60 && iGrade < 70)
chReturnValue = ‘D’;
else // given Assertion, iGrade must be < 60
chReturnValue = ‘F’;
return (chReturnValue);
} // of letterGrade
Is this right?
Writing Methods--Flawed Example
/**
* Calculate the recurrence relation, r(n) = r(n-1) +
* r(n-2) - r(n-3), where: r(1)=1, r(2)=2, r(3)=3, n>=1.
* @param is the value of recurrence relation to calculate.
* @return the integer value of the recurrence relation at n.
*/
public int recurrence (int iN) {
What’s wrong
int iReturnVal = 0;
with it?
util.ASSERT(iN >= 1, “int param is less than 1”);
if (iN == 1) iReturnVal = 1;
else if (iN == 2) iReturnVal = 2;
else if (iN == 3) iReturnVal = 3;
else
iReturnVal = recurrence (iN-1) +
recurrence(iN-2) - recurrence(iN-3);
return (iReturnVal);
} // of recurrence
Writing Methods--Repaired Example
/**
* Calculate the recurrence relation, r(n) = r(n-1) +
* r(n-2) - r(n-3), where: r(1)=1, r(2)=2, r(3)=3, n>=1.
* @param is the value of recurrence relation to calculate.
* @return the integer value of the recurrence relation at n.
*/
public int recurrence (int iN)
{
util.ASSERT ( iN >= 1, “int param is less than 1”);
return (iN);
} // of recurrence
Lesson: while creating code that
works, remember to think!
Classes and Objects
Class:
describes the form of an object,
a template or blueprint or mold
specifies data representation,
behavior, and inheritance (via
variables, methods and parents)
Object:
an instance of a class
--has unique copy of every nonstatic variable (i.e., the
“instance variables” but not the
class variables).
Difference between “a class and an object of
that class” is analogous to the difference
between “a type and a variable of that type”.
Naming Conventions:
Classes: Identifiers begin with cap letters for
each word in the Identifier,
e.g., NeuralNetwork.java
Objects: Identifiers begins with lower case letter,
then caps for other words in identifier,
e.g., myObjectIdentifier
KEY CONCEPT
Java Data Structures
In Java, any data structure that is not a
primitive must be an object of some class.
Thus, to create what is logically a record, define a class (ala a type),
specifying both:
the data fields of the record
all the methods that can act upon those data.
Because we can use a class to encapsulate
both the data and the methods associated
with the what would be a record, there is no
need for a record construct.
Java doesn’t need a record construct
Java doesn’t have a record construct.
Instead, one implements records
(with methods) as a class.
Evolution of an Object: An Example
Pseudocode:
length isoftype Num
read(length)
width isoftype Num
read(width)
height isoftype Num
read(height)
volume isoftype Num
volume <- length * width * height
Pro:
Straightforward, no special
techniques
Con:
No data type; no reusability,
cannot create multiples of it.
Poor abstraction (none, except
for data identifiers)
Evolution of an Object (cont’d)
Box_Type definesa record
length isoftype Num
width isoftype Num
height isoftype Num
volume isoftype Num
endrecord
this_box isoftype Box_Type
Pro:
Grouping of data, better data
abstraction: box as data entity,
not just a set of variables.
More reusable: can easily get
multiple boxes
read(this_box.length, this_box.width,
this_box.height)
this_box.volume <- this_box.length *
this_box.width*this_box.height
Con:
Direct manipulation of data
Low procedural abstraction: must think about
“how to do it?” instead of “what I want to do?”
Evolution of an Object (cont’d)
How to model a box?
class Box {
int iLength;
int iWidth;
int iHeight;
(Java example)
Instance variables
(because they’re not
static)
public void setLength (int iNewLength) {
util.ASSERT (iNewLength > 0, “iNewLength <= 0”);
iLength = iNewLength;
} // of setLength
public void setWidth (int iNewWidth) {
util.ASSERT (iNewWidth > 0,
“iNewWidth <= 0”);
iWidth = iNewWidth;
} // of setWidth
public int getLength ( ) {
return (iLength);
} // of getLength
Method to
get
(‘access’)
instance
variable
Methods
to
change
(‘modify’)
instance
variables
Evolution of an Object (cont’d)
How to model a box?
(Java example cont’d)
public void setHeight (int iNewHeight) {
util.ASSERT (iNewHeight > 0, “iNewHeight <= 0”);
iHeight = iNewHeight;
} // of setHeight
public int getWidth ( ) {
return (iWidth);
} // of getWidth
public int getHeight ( ) {
return (iHeight);
} // of getHeight
public int getVolume ( ) {
return ( getLength( ) *
getWidth( ) * getHeight( ) );
} // of getVolume
} // of class Box
Methods to get
(‘access’)
instance
variables
Object Terminology
“Accessor” and “Modifier” Methods: “state objects.”
They return a value about
the state of an object.
Accessor Methods:
The “get” methods . . .
( The identifier name
prefix “get” not required,
but is preferred practice. )
They can return a variable value,
and can return something that is
calculated (e.g. getVolume; no need
for an iVolume attribute).
Modifier Methods:
The “set” methods . . .
( The identifier name prefix ‘set” not
required, but is preferred practice. )
Allows us to restrict access to variables
and thereby control their values.
(Otherwise, we would have to include
util.ASSERT statements everywhere!)
Using Objects: Creating a Box
class BoxesExample {
public static void main (String[ ] argv) {
Box shoeBox;
shoeBox = new Box( );
shoeBox.setLength(35);
shoeBox.setWidth(19);
shoeBox.setHeight(13);
Box cdBox = new Box( );
cdBox.setLength(14);
cdBox.setWidth(9);
cdBox.setHeight(1);
int iTotalVolumeOfBoxes;
iTotalVolumeOfBoxes =
shoeBox.getVolume()
+ cdBox.getVolume();
System.out.println
(“The combined volume of the boxes”);
System.out.println
(“is: “, iTotalVolumeOfBoxes);
} // of main
} // of class BoxesExampleProgram
A second class is used
to create an instance
of our box class.
The BoxesExample
class has a main
method, and is run
as a program
Using Objects: Creating a Box
class BoxesExample {
public static void main (String[ ] argv) {
Box shoeBox;
shoeBox = new Box( );
shoeBox.setLength(35);
shoeBox.setWidth(19);
shoeBox.setHeight(13);
Box cdBox = new Box( );
cdBox.setLength(14);
cdBox.setWidth(9);
cdBox.setHeight(1);
First, we declare
a variable
called ‘shoeBox.’
At this point, shoeBox
is merely a null
reference.
Second, we
instantiate shoeBox.
Values are assigned.
int iTotalVolumeOfBoxes;
iTotalVolumeOfBoxes =
shoeBox.getVolume()
+ cdBox.getVolume();
System.out.println
(“The combined volume of the boxes”);
System.out.println
(“is: “, iTotalVolumeOfBoxes);
} // of main
} // of class BoxesExampleProgram
Using Objects: Creating a Box
class BoxesExample {
public static void main (String[ ] argv) {
Box shoeBox;
shoeBox = new Box( );
shoeBox.setLength(35);
shoeBox.setWidth(19);
shoeBox.setHeight(13);
Box cdBox = new Box( );
cdBox.setLength(14);
cdBox.setWidth(9);
cdBox.setHeight(1);
int iTotalVolumeOfBoxes;
iTotalVolumeOfBoxes =
shoeBox.getVolume()
+ cdBox.getVolume();
System.out.println
(“The combined volume of the boxes”);
System.out.println
(“is: “, iTotalVolumeOfBoxes);
} // of main
} // of class BoxesExampleProgram
These steps are
repeated for our
next variable,
cdBox. Note that the
1st two steps are here
collapsed into
one line:
Declaration &
Instantiation
Using Objects: Creating a Box
class BoxesExample {
public static void main (String[ ] argv) {
Box shoeBox;
shoeBox = new Box( );
shoeBox.setLength(35);
shoeBox.setWidth(19);
shoeBox.setHeight(13);
Box cdBox = new Box( );
cdBox.setLength(14);
cdBox.setWidth(9);
cdBox.setHeight(1);
int iTotalVolumeOfBoxes;
iTotalVolumeOfBoxes =
shoeBox.getVolume()
+ cdBox.getVolume();
System.out.println
(“The combined volume of the boxes”);
System.out.println
(“is: “, iTotalVolumeOfBoxes);
} // of main
} // of class BoxesExampleProgram
Another variable
is declared
and assigned a value.
NOTE: We obtain
information about
the box ONLY through
it’s accessor methods
Using Objects: Creating a Box
class BoxesExample {
public static void main (String[ ] argv) {
Box shoeBox;
shoeBox = new Box( );
shoeBox.setLength(35);
shoeBox.setWidth(19);
shoeBox.setHeight(13);
Box cdBox = new Box( );
cdBox.setLength(14);
cdBox.setWidth(9);
cdBox.setHeight(1);
int iTotalVolumeOfBoxes;
iTotalVolumeOfBoxes =
shoeBox.getVolume()
+ cdBox.getVolume();
System.out.println
(“The combined volume of the boxes”);
System.out.println
(“is: “, iTotalVolumeOfBoxes);
} // of main
} // of class BoxesExampleProgram
Comments:
1. Variable declaration and assignment
is mixed together. A more complex
program might require better organization
2. “Hybrid OO”: We have classes, but
everything occurs within a static method,
“main”, making things linear. This is fine
for small programs, but larger programs
would benefit from “Pure OO”. Keep this
in mind; it becomes very important later.
Review: Our Box Model
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
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
public int getHeight ( ) {
return (iHeight);
} // of getHeight
public int getVolume ( ) {
return ( getLength( ) * getWidth( )
* getHeight( ) );
} // of getVolume
} // of class Box
Declaring 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.
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
Objects and References
So far, we have:
Box shoeBox;
shoeBox
• To make the reference shoeBox be not null,
it is necessary to instantiate it, e.g.,
shoeBox
shoeBox = new Box( );
an instance
of class Box
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. (The methods are
shared between all instance of the class, but
Java knows which instance you are referring
to.)
Objects and 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)
Objects and References
Box shoeBox
= new Box();
Box cdBox
= new Box();
Box present
= new Box();
shoeBox
The data fields (“attributes”):
int iLength;
int iWidth;
int iHeight;
cdBox
What can be done to that data
The data(“methods”):
fields (“attributes”):
int iLength;
public void setLength (int iNewLength)
int iWidth;
public int getLength ( )
int iHeight;
public void setWidth (int iNewWidth)
public int getWidth ( )
What canpublic
be done
that data (int iNewHeight)
voidtosetHeight
(“methods”):
public int getHeight ( )
The data fields (“attributes”):
public
void
setLength
(int iNewLength)
public
int getVolume
()
int iLength;
public
int
getLength
(
)
int iWidth;
public void setWidth (int iNewWidth)
int iHeight;
public int getWidth ( )
What can be donepublic
to thatvoid
datasetHeight (int iNewHeight)
public int getHeight ( )
(“methods”):
public
getVolume ( )
public void setLength
(intintiNewLength)
public int getLength ( )
public void setWidth (int iNewWidth)
public int getWidth ( )
present
...
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!
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.)
Objects and References
What 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:
shoeBox.setLength(35);
shoeBox.setWidth(19);
shoeBox.setHeight(13);
is equivalent to the pseudocode:
shoeBox^.setLength(35)
shoeBox^.setWidth(19)
shoeBox^.setHeight(13)
References 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:
There exists no way to explicitly manipulate pointers. There is no
explicit dereferencing operator
So:
if you don’t know about pointers, then
references are “magic”
if you do understand pointers, then
you know what references really are!
Calling (or Invoking) Methods
•Restrictions:
class CompanyStock {
public double getAmountEarned ( ) {
double dOpen = getOpenValue();
/* calls method in this class */
double dClose = getCloseValue();
/* calls method in this class */
. . .//etc. etc.
} // of getAmountEarned
public double getOpenValue() {
return 1234.5d;
}
public double getCloseValue(){
return 2345.6d;
}
} // of CompanyStock
1. Invocation must be
unambiguous re: which object
or class the method is to act
upon.
2. If the method call appears
inside a class, then that class is
presumed to contain the
appropriate method:
Calling (or Invoking) Methods
• If the method is NOT inside the class where method declared,
then the object must be specified.
class WallstreetJitters {
public void panicSell ( ) {
Greenspan fedChair
= new Greenspan();
if (fedChair.raisesInterest())
{
buyOnMargin();
}
else
{
sellAllStock();
}
} // of panicSell
} // of WallstreetJitters
FORMAT:
<object reference>.<method name>
Greenspan
class must
have this
method!
These methods
must appear in
this class!
Java Constructors
Motivation:
We need a means of initializing
the attributes of a new object (or
“instance”) when it is created.
Means:
“Constructor 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
Note: Constructor method has same
identification as the class.
Can now do:
Box subwooferBox =
new Box (46, 46, 82);
Equivalent to:
Box subwooferBox = new Box;
subwooferBox.setLength(46);
subwooferBox.setWidth(46);
subwooferBox.setHeight(82);
Java Constructors
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.”
Such that:
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)
We can:
String strInput1 = new String ( );
String strInput2 = new String
(“A valid constructor.”);
class person {
String strName;
int
iAge;
Java Constructors:
Another Example
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
Java 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. Can’t tell which one to invoke.
Java Constructors
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
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
won’t be auto-invoked.
Nope!
Creating 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);
Objects and References
Distinguish between primitives and objects.
Assignment with Primitives:
Code:
int x;
int y;
Memory:
x
x
y
iThis = 5;
x=5
y
iThat = iThis;
x=5
y=5
Objects and References
Assignment with References to Objects:
Code:
Memory:
Box box1;
Box box2;
box1
box2
box1 = new Box(8, 5, 7);
box1
L=8, W=5, H=7
box2
box2 = box1;
// note: two references
// but only one object
box1 =
new Box(3, 9, 2);
box1 = box2;
// Old reference lost!
box1
L=8, W=5, H=7
box2
box1
L=3, W=9, H=2
box2
L=8, W=5, H=7
box1
L=3, W=9, H=2
box2
L=8, W=5, H=7
Instance vs. Class Declarations
A distinction that applies to both:
• variables
• 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 Variables
Suppose we wanted to track the total number of objects created.
Consider:
class Human {
String strName;
int iPopulation = 0;
Declares a strName String for
each instance .
Thus, each Human will have its
own name.
public Human (String strName) {
this.strName = strName;
iPopulation++; //WRONG!
} // of constructor
} // of Human
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
one. This makes no sense!
Instance 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.
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.
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 single
constant for use by
all instances of the
class.
Declares a different-butidentical constant
for each instance of the
class.
Wasteful with zero
benefit.
Objects vs. References--An Example
class MyObject {
String name;
public MyObject (String n) {
name = n;
}
public String toString () {
return (name);
}
}
public class SwapTester {
public static void swapInt (int x, int y) {
int temp;
System.out.println ("Doing swapInt");
temp = x;
x = y;
y = temp;
}
/* in class Basics (cont’d) . . . */
public static void swapObject1 (MyObject x, MyObject y) {
MyObject temp;
System.out.println ("Doing swapObject1");
temp = x;
x = y;
y = temp;
}
public static void swapObject2 (MyObject x, MyObject y) {
MyObject temp = new MyObject ("temp");
System.out.println ("Doing swapObject2");
temp.name = x.name;
x.name = y.name;
y.name = temp.name;
}// swapObject2
/* in class SwapTester (cont’d) . . . */
public static void main (String argv[]) {
int x, y, z; x = 5; y = 10; z = y; y = 5;
System.out.println ("x=" + x + " y=" + y + " z=" + z);
System.out.println ("x==5 is " + (x==5));
System.out.println ("x==y is " + (x==y));
System.out.println ("y==z is " + (y==z));
swapInt (x, z);
System.out.println ("x=" + x + " y=" + y + " z=" + z);
System.out.println ();
Output for this portion of the program:
x=5 y=5 z=10
x==5 is true
x==y is true
y==z is false
Doing swapInt
x=5 y=5 z=10
/* in class SwapTester’s main method (cont’d) . . . */
String a, b, c;
a = "hello";
b = new String ("hello");
c = b;
System.out.println ("a=" + a + " b=" + b + " c=" + c);
System.out.println ("a==hello is " + (a=="hello"));
System.out.println ("b==hello is " + (b=="hello"));
System.out.println ("a==b is " + (a==b));
System.out.println ("a.equals(b) is " + (a.equals(b)));
System.out.println ("b==c is " + (b==c));
System.out.println ("b.equals(c) is " + (b.equals(c)));
System.out.println ();
Output
a=hello b=hello c=hello
a==hello is true
b==hello is false
a==b is false
a.equals(b) is true
b==c is true
b.equals(c) is true
/* in class SwapTester’s main method (cont’d) . . . */
MyObject p, q, r, s;
p = new MyObject ("hello");
q = new MyObject ("hello"); r = q;
s = new MyObject ("world");
System.out.println ("p=" + p + " q=" + q + " r=" + r + " s=" + s);
System.out.println ("p==q is " + (p==q));
System.out.println ("q==r is " + (q==r));
swapObject1 (p, s);
System.out.println ("p=" + p + " q=" + q + " r=" + r + " s=" + s);
swapObject2 (p, s);
System.out.println ("p=" + p + " q=" + q + " r=" + r + " s=" + s);
}// end of main
}// class SwapTester
Output:
p=hello q=hello r=hello s=world
p==q is false
q==r is true
Doing swapObject1
p=hello q=hello r=hello s=world
Doing swapObject2
p=world q=hello r=hello s=hello
Objects vs. References: Summary
Key Concepts:
= and == with objects and references.
Parameter passing, call by value, call by constant
reference.
Summary:
Java has no pointers, only references.
Null is a special value that means "no object" or
"absenceof reference”.
All objects and arrays (i.e., everyting except
primitivetypes) are handled by reference
= assigns references to objects
(use clone() to copy theobject itself).
== and != test references with references
(use equals() totest the objects themselves).
Descargar

GSAMS - Georgia Institute of Technology