java application prerequisite review 1renzo/cs182/prerequisitereview.pdf · java application...
Post on 26-Mar-2018
220 Views
Preview:
TRANSCRIPT
prerequisite review 1
Object
variable
primitive
object
Method
constructor
accessor
mutator
...
Method
main
Java Application
Application Object
prerequisite review 2
application : = [class] 1
class := [instance variables]* + [ methods ] *
instance variables := primitive types || object
primitive type := int, double, boolean, char
object := [ ], String, Class_type
method := arguments, local instance variables +
statements + structured statements
[term] * 0 or more occurances
[term] 1 1 or more occurances
Java syntactically
prerequisite review 3
problem solving by programming
design, edit / code, compile / debug, run, walk through, test
applications (programs)
type variable, class defines a data type for objects,
method return type
variable primitive type – int, double, char, boolean
array, string, object,
reference scope {class, method, block}
statement simple, structured
simple assignment, {s; s; s; s;}, return, method call
structured branching / decision, repetition / looping
methods constructor, accessor (get), mutator (set), ...
class user defined Data Type,
composition, “has-a”
inheritance, “is –a”, extends
OOP Programming Concepts
prerequisite review 4
initialization constructors, null pointer exception
choice if(boolean expression), logical assertions and
relational comparisons. switch(scalarValue)
iteration loops, process elements in an array, sort(),
find(<type> target), hasNext*(),
while ( inputLine != null), for(pre; test; post)
selection array[index], substring(...), aString.charAt(index)
concatenation +, strings, toString()
recursion method calls itself, directly or indirectly
stopping, continuation conditions.
factorial, binary search
input/output type conversion Integer.parseInt(string),
println(), printf(), split, Scanner, PrintWriter
throws IOException, file IO
design patterns / techniques
prerequisite review 5
composition "has - a" object relationships
reuse of class definitions with variable
inheritance "is - a" class relationships
reuse with extension of class definitions
decomposition design method to solve simpler problem,
"factor" common code into methods
parameterize methods with arguments
reuse use static and dynamic methods and classes
in Java packages, Math.random() Vs Random
write classes that can be reused by application
exceptions try - catch, null pointer exception, file IO,
run time system error event messages
design patters / approaches
prerequisite review 6UML Diagrams
ClassName
- privateVariable : type
# protectedVariable : type
+ publicVariable : type
+ Constructor(arguments)
- privateMethod(args) : type
# protectedMethod(args) : type
+ publicMethod(args) : type
Abstract Class
AncestorClass
DescendantClass
ApplicationClass* 1
composition
has – an
array, collection
inheritance
is – a
super
factoring
inheritance
is – a
super
factoring must override inherited
abstract methods
prerequisite review 7Object Oriented Programming
A design and programming technique
Some terminology:
object - usually a person, place or thing (a noun)
method - an action performed by an object (a verb)
type or class - a category of similar objects (such as
automobiles)
Objects have both data (variables) and methods (“functions”)
Objects of the same class have the same data elements and methods
Saves development time (and cost) by reusing code
once an object class is created it can be used in other applications
Easier debugging
classes can be tested independently
reused objects have already been tested
prerequisite review 8
Algorithms solve a problem (more than one solution)
Algorithm = steps (instructions) + resources (data)
complete all data required, all steps needed
specific sequence / control of steps, amount / types of steps
Algorithm formats (one is not enough)
natural language (ie English)
programming language (Java)
diagram, flow chart, block flow, UML
pseudocode -- mix of natural and programming language
Programming a solution
algorithm design
implementation plan order of sub-problems to implement / test
verification test cases to check correctness
Solve problems
prerequisite review 9Problem Solving
Design, then code – avoid the rush to judgment!
Design process
define the problem clearly
design objects your program needs
develop algorithms for the methods of objects
describe the algorithms, usually in pseudocode
write the code
test the code
Fix any errors and retest and often redesign.
Solve a Simpler Problem First
Break larger task into smaller parts
Solve each part, program each part, test each part
Combine the parts.
Think of another approach or design solution
prerequisite review 10Variables, Types, Operators, Expressions
Variables
store (hold) information
have a name (way to reference)
have a value (binary )
have a type – know primitive types: boolean, int, float, ...
how to interpret value
how much memory is needed to store value
must be declared before they are used.
specify both type and name
Implicit casting – convert from "lower" to "higher" scalar type
no data loss. floatVariable = intVariable;
Explicit casting – convert from "higher" type to "lower" type
can lose information. intVariable = (int) floatVariable;
Expression resolve to values. Expressions have types.
public static final double PI = 3.14159; // what is this?
prerequisite review 11Structured Statements
Flow of Control is the execution order of instructions in methods.
All programs can be written with three control flow elements:
1. Sequence - execute next instruction
2. Selection - a choice of at least two
either go to the next instruction
or jump to some other instruction
3. Repetition - a loop (repeat a block of code)
At the end of the loop:
either go back and repeat the block of code
or continue with the next instruction after the block
Selection and Repetition are called Branching statements since these
are branch points in the program's flow of control.
Know: if (if then else, if then elseif else), switch, while, do, for
Know: break, continue
prerequisite review 12Methods
Methods are defined before used. [ ] optional, < > substitute
[ <accessibility> ] [ <modifier> ] <return-type> <name>
( <argument-list> ) { < body > }
public void paint(Graphics g) {
g.setColor(Color.red);
g.fillRect( 30, 50, 100, 200); }
Arguments match in type and number between method call and method
definition.
Static methods (called by ClassName.methodName)
callable w/o object instantiation. Math.random();
Abstract methods have no body – inside abstract class.
Descendants must define method.ViewPoly's public abstract void paint(Graphics g);
Polymorphic method calls use abstract methods and inheritance.
prerequisite review 13Classes, Inheritance
Every Java program has at least one class.
A class is a declaration of an object's type -- it defines a new type,
extends the programming language!
Classes have
instance variables (data, nouns) – "has-a" relationships.
methods (actions, verbs)
Inheritance – class can "reuse" or extend the type of another class.
defines an "is-a" relationship. Child class "is-a" Parent class type.
Classes have constructors used to "create" and initialize objects.
Method overloading – more than 1 class with same type and name w/in
class, but different arguments. Constructors are often overloaded.
Method overriding – method is "redefined" in a descendant (subclass
Class and method definitions define scope
prerequisite review 14
Object creation with new calls a special method -- a constructor
that constructs the object.
Constructors do not have a return type.
Constructors have the same name as the class.
Constructors often take arguments to set the initial values of the object's
variables.
public <name> ( <argument-list>) { <body> }
If there is no constructor defined a default constructor creates an object
without any initialization (arguments).
super(<argument-list>), super.<name> <argument-list>)
used to call a class's parent class constructor, or method
keyword this is used to refer to the current object in its constructor.
It can be optionally be used anywhere inside the class;s body.
Constructors
prerequisite review 15
java ScopeEG
i
main (....) i j
ScopeEG ( int k )
j
i = k;
aMethod ( )j
new ScopeEG(10)
aMethod()
Executing a Java class
file is a call to the class's
main() method
One private instance
variable named "i"
declared in the body of
the class and one local
variable named "i"
declared in the main
method.
One private method
aMethod().
Scope
prerequisite review 16Accessibility – 4 Ps
Classes, instance variables and methods can be defined with
accessibility descriptions of "visibility – usability ".
Accessibility (scope): private, protected, package (default), public
Accessibility helps to protect (hide information) in a collection of
classes from unintended changes. If you can’t modify, you can't hurt.
UML (unified modeling language) "lite" diagrams for classes
ClassName
- privateVariable : type
# protectedVariable : type
+ publicVariable : type
+ Constructor(arguments)
- privateMethod(args) : type
# protectedMethod(args) : type
+ publicMethod(args) : type
Shape
# x : int
# y : int
# color : Color
+ Shape(int, int, Color)
+ draw(Graphic) : void
prerequisite review 17
Arrays are objects.
Arrays are a collection of same typed values.
Individual values in the array are referenced with <name>[<index>]
where the index is an int value ranging from 0 to arraySize -1
<type> [] < array name > = new < type > [< length >];
<type> [] < array name > ; // size allocation deferred
Multi-dimensional Arrays.
2 D array is a 1 D array where each cell is a 1 D array
3 D array is a 1 D array where each cell is a 2 D array
String class represents a sequence of character values and has methods
that can be applied to string objects. A string is a sequence of char.
String sayHi = "Hello Stranger!";
char aChar = sayHi.charAt(14); // '!'
String subStr = sayHi.substring(8,11); // ran
String [] tokens = sayHi.split(“\\s”); // tokenize string
Arrays, Strings
prerequisite review 18Errors
Syntax Found by compiler.
Easiest error to solve.
Error message may be hard to understand
Solved by editing / recompiling
Run-time Found during program testing
file not found, divide by zero
Costly are infrequent situations, not found in testing
Occurance terminates program (rudely)
Handled by try / catch exception blocks
Logical Found during program validation – trace, walkthroughs
Costly are not found – decisions made on incorrect results!
Handled by civil and criminal justice system.
prerequisite review 19I/0, exceptions
System.out
programSystem.in
System.err
keyboard console
System.out.println(string expression) basic output statement
variables converted with toString() and can be formatted.
Scanner can be used for input from the keyboard and files.
PrintWriter class can be used to write to files.
Input / Ouput can cause system traps – exceptions to be thrown.try {
stmts that may throw an exception
resource acquiring stmts }
catch ( AnException except) {
exception handling stmts;}
finally {
stmts executed after either try or try-catch
release resources stmts;}
see FileExceptionDemo.java
terence.txt
prerequisite review 20
Polymorphism means multiple possible states for a single property.
In Object Oriented Programming languages it refers to type
polymorphism – where subclass objects can be treated as a superclass
type.
This is often useful when you have collections (array) of objects that you
want to apply an operation to, but where the operation is slightly different
for each object.
For example consider a collection of different shape objects – that all
descend (extend) from the abstract class Shape with an abstract draw
method.
For example: Square extends Shape and Rectangle extends Square.
Thus, Square and Rectangle are all "Shapes" and can be held in an array
(collection) of Shapes.
The draw method of Shape could be used to draw all "Shape" objects.
Polymorphism
prerequisite review 21
Shape
Square
Rectangle
ViewPoly* 1
1 large blue square
1 large red square
4 small green squares
2 white rectangles
1 ViewPoly can have
* (many) Shapes
Shape is an abstract
class
Square extends Shape
Rectangle extends
Square
ViewPoly class diagram
has -a
is -a
Comp182Window
Frame
prerequisite review 22Shape
// Definition of an abstract shape
abstract class Shape {
protected int x, y;
protected Color color;
public Shape(int anX, int aY, Color aColor) {
x = anX;
y = aY;
color = aColor;
}
// abstract methods must be implemented in sub-classes
// Graphics is a Java API class for 2D drawing
public abstract void draw(Graphics g);
}
prerequisite review 23Square
// Definition of a square shape
class Square extends Shape {
protected int side1;
public Square(int anX, int aY, Color color, int s) {
super(anX, aY, color);
side1 = s;
}
public void draw(Graphics g) {
g.setColor(color);
g.fillRect(x, y, side1, side1);
}
}
prerequisite review 24Rectangle
// Definition of a rectangle shape
class Rectangle extends Square {
private int side2;
public Rectangle (int anX, int aY, Color color,
int s1, int s2)
{
super(anX, aY, color, s1);
side2 = s2;
}
public void draw(Graphics g) {
g.setColor(color);
g.fillRect(x, y, side1, side2);
}
}
prerequisite review 25
// This is not the entire file – just an example
public class ViewPoly extends Comp182Window {
private Shape[] scene;
public ViewPoly(String title, int x, int y, int n) {
super(title, x, y);
// array space size allocated by program
scene = new Shape[n];
// assume "n" "Shapes" have been inserted in scene
}
public void paint(Graphics g) {
for(int i = 0; i < scene.length; i++) scene[i].draw(g);
}
public static void Main (String [] args) {
ViewPoly vp =
new ViewPoly("Polymorphic Draw", 400, 400, 10);
...
}
}
ViewPoly
prerequisite review 26
// In ViewPoly.java
public void paint(Graphics g) {
for(int i = 0; i < scene.length; i++)
scene[i].draw(g);
}
Shape Shape Shape Shape Shape Shape Shape Shape
Rectangle
draw(g) : void
Square
draw(g) : void
Square
draw(g) : void
Square
draw(g) : void
Rectangle
draw(g) : void
ViewPoly diagram
prerequisite review 27Rectangle’s members
side2
Rectangle
Rectangle(int, int, Color, int, int)
Square
side1
Square (int, int, Color, int)
Shape
x
Shape (int, int, Color)
y color
Rectangle is-a Square
Rectangle is-a Shape
Square is-a Shape
Rectangles and
Squares
can be contained
by collections
(arrays) that hold
Shapes
prerequisite review 28Recursion
Recursion occurs when a method calls itself.
Consider method int fac(int) // assumes argument > 0
public class RecursiveFac {
public int fac(int n) {
System.out.println("fac(" + n + ")");
if (n == 1) return 1;
return n * fac(n-1);
}
}
…
RecursiveFac rf = new RecursiveFac();
System.out.println(rf.fac(4));
fac(4)
fac(3)
fac(2)
fac(1)
24
call return
fac(4) 24 = 4 * 6
fac(3) 6 = 3 * 2
fac(2) 2 = 2 * 1
fac(1) 1
recursive
descentrecursive
ascent
halting state
prerequisite review 29Binary Search
Consider searching for a target value in a sorted array
public class BinarySearch {
int [] array;
int size = 0;
public BinarySearch(int n) {
size = n;
array = new int[size];
System.out.print("array == ");
for(int i = 0; i < size; i++) {
array[i] = i;
System.out.print(array[i] + " "); }
System.out.println();
}
public void find (int value) {
int returnIndex, notFoundIndex = -1;
returnIndex = found(value, 0, size-1);
if (notFoundIndex == returnIndex)
System.out.println(value + " not found");
else
System.out.println(value + " found at array[" +
returnIndex + "]");
}
prerequisite review 30found(...)
private int found(int value, int start, int stop) {
int i = start + (stop - start)/2;
System.out.println("found(" + value + "," + start +
"," + stop +")");
if (value == array[i]) // found value ?
return i; // halt, return index of value
else if (start == i) // looked at all values
return -1; // halt, return not found index
else if (value < array[i]) // search lesser half
return found(value, start, i);
else // search greater half
return found(value, i + 1, stop);
}}
> BinarySearch bs = new BinarySearch(7);
array == 0 1 2 3 4 5 6
> bs.find(1);
found(1,0,6)
found(1,0,3)
1 found at array[1]
>
Fibonacci number
𝐹𝑖𝑏 𝑛 = 1
𝐹𝑖𝑏 𝑛 − 1 + 𝐹𝑖𝑏(𝑛 − 2)𝑤ℎ𝑒𝑛 𝑛 ≤ 2𝑤ℎ𝑒𝑛 𝑛 > 2
Write a java program to compute the Fibonacci number for "n"
(without using internet search, textbooks, etc)
for example
Fib(3) = 2 or fib(2) + fib(1)
1 + 1
Fib(4) = 3 or fib(3) + fib(2)
fib(2) + fib(1) + 1
1 + 1
Fib(6) = 8 or fib(5) + fib(4)
fib(4) + fib(3) + fib(3) + fib(2)
3 + 2 + 2 + 1
Fib(10) = 55
prerequisite review 31
prerequisite review 32Performance
Algorithms can be evaluated on their performance.
We can compare search algorithms on the number of comparison made.
Consider linear searching for a value that is in an array.
best case 1 first cell has search value
worst case n last cell has search value
average case n/2 position is equally likely, over many
searches the average would be n/2
Now lets also assume the array is sorted and we use a binary search
best case 1 middle cell has search value
worst case log(n,2) last cell searched
average case log(n,2) -1 this is half the worst case searches
n
best average worst
linear binary linear binary linear binary
16 1 1 8 3 16 4
64 1 1 32 5 64 6
prerequisite review 33Java Programs and Classes
All java applications have at least one class definition that has a static
main method (where execution begins).
Every Java class definition is stored in a file. The file name must be
the same as the class's name and end with a *.java extension. The
class must be public and its name must start with a uppercase letter.
There can be multiple class definitions within a single *.java file.
There are usually java import statements that specify where class
packages that are referenced in the file are located on the system.
The keyword "extends" is used in the declaration of a class (child
class or subclass) that will inherit (re-use) type declarations of an
existing class (parent class or super-class). An "is-a" relationship.
If a class is abstract you cannot be instantiated ( create an object of
that class type). If a class has an abstract method it must declared as
an abstract class.
prerequisite review 34Classes and Methods
Every class definition can contain several instance variable declarations
(with possible initializations) and method definitions.
Instance variables have scope across the entire class and are declared
outside of any method definition.
Method definitions can contain local variables that are declared inside
the body of the method. Local variables hide (shadow or have
precedence over instance variables with the same name).
Method arguments are like local variables that have been initialized.
Methods definitions can be overloaded within the same class definition.
All method signatures must be unique.
Inherited method definitions can be overridden in a sub-class (child
class within a class inheritance relationship).
Inherited abstract methods must be defined in sub-classes.
prerequisite review 35Design
Overloading allows us to have methods that perform the same action
with different arguments (input variables) with the same return type and
name.
We can use appropriate method names – we don't have to make up
names just for them to be different – setDate
Overriding allows us to use the same method signature (type, name,
and arguments) with different actions (statements in the body) in
decendant classes. The method defined in the class "hides" or
"shadows" the one that is inherited. It is used instead.
Factor (simplify) your design
Factor out common instance variables and methods with
inheritance. Move factored terms to super class.
Factor out common (duplicate) code in a class by creating a
"helper" or "utility" method. Often this method is private
prerequisite review 36Transparency
While algorithms are evaluated on their performance, program design
and implementation is evaluated on its correctness and transparency:
Correctness – does the design / implementation work correctly,
it does what it was designed for and it does it without error.
Transparency of design and implementation
Readable – is the design, and implementation readable,
documented
Maintainable -- does the design and implementation facilitate
updates, improvements and extensions to the program's
capabilities
Usable – how well does the design and implementation
support ease of learning and use.
prerequisite review 37HTML – web pages
Web pages are text files with embedded HTML (Hyper Text Markup
Language) tags. Tags: <tag> .... </tag>
File has extension *.html or *.htm -- view source class pages
Common layout of tags for a web page:
<html>
<head>
<title> title text here </title>
</head>
<body>
<h1> Six levels (sizes) of headers </h1>
<p> Paragraphs </p>
<ul>
<li> unordered, bullet list item
<li> use tag <ol> for ordered list items
</ul>
</body>
</html> View source for Comp182.htm page
prerequisite review 38Javadoc
Javadoc is tool (program) that reads a java source file and generates on-
line documentation. It can include HTML tags. APIs often generate...
/**
* An example <b> doc </b> comment.
* @author G. M. Barnes
*/
A doc comment is written in HTML within the program souce file and
must precede a class, constructor, method, or field declaration.
It is made up of two parts -- a description followed by block tags:
@param (classes, interfaces, methods and constructors only)
@return (methods only)
@exception (or @throws)
@author (classes and interfaces only)
@version (classes and interfaces only)
@see
@since see JavadocExample.java & its documentation
prerequisite review 39jar files
Jar stands for Java ARchive. It's a file format based on the popular ZIP
file format and is used for aggregating many files into one.
Jar is:
• an archive format that is cross-platform
• a format that handles class, audio, and image files
• backward-compatible with existing applet code
• an open standard, fully extendable, and written in java
• the preferred way to bundle the pieces of a java applet
Command Purposejar cf file.jar inputFile(s) create file.jar
jar tf file.jar view files
jar xf file.jar extract files
How to make executable jar files
jar cvfm MyJarName.jar manifest.txt *.class
manifest.txt 1 line specifies file with main method
Main-Class: fileWithMainClass
top related