Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Java Application prerequisite review Object variable primitive object Method constructor accessor mutator ... Method main 1 Java syntactically application : = [class] 1 class := [instance variables]* prerequisite review + [ 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] [term] * 1 0 or more occurances 1 or more occurances 2 OOP Programming Concepts problem solving by programming prerequisite review 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 methods simple, structured assignment, {s; s; s; s;}, return, method call branching / decsion, repetition / looping constructor, accessor (get), mutator (set), ... class user defined Data Type, composition, “has-a” inheritance, “is –a”, extends 3 design patterns / techniques prerequisite review 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 4 design patters / approaches prerequisite review 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 5 prerequisite review UML Diagrams Abstract Class inheritance is – a super factoring 1 * composition has – a array, collections ApplicationClass must override inherited abstract methods AncestorClass inheritance is – a super factoring DescendantClass ClassName - privateVariable : type # protectedVariable : type + publicVariable : type + # + Constructor(arguments) privateMethod(args) : type protectedMethod(args) : type publicMethod(args) : type 6 Object Oriented Programming prerequisite review 7 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 Solve problems prerequisite review 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 8 Problem Solving prerequisite review 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 9 Variables, Types, Operators, Expressions prerequisite review 10 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? Structured Statements prerequisite review 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 11 prerequisite review Methods 12 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. Classes, Inheritance prerequisite review 13 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 signature w/in class. Constructors are often overloadded. Method overridding – method is "redefined" in a descendant Class and method definitions define scope (subclass) Constructors 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. prerequisite review Scope java ScopeEG 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(). main (....) i j new ScopeEG(10) aMethod() ScopeEG ( int k ) i = k; j aMethod ( ) i j 15 Accessibility – 4 Ps prerequisite review 16 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 Arrays, Strings prerequisite review 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 17 Errors prerequisite review 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. 18 prerequisite review System.out I/0, exceptions keyboard System.in program 19 console System.err 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;} Polymorphism prerequisite review 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. 20 prerequisite review ViewPoly class diagram Frame Comp182Window * Shape 1 has -a ViewPoly is -a Square 1 ViewPoly can have * (many) Shapes Shape is an abstract class Rectangle Square extends Shape Rectangle extends Square 1 large blue square 1 large red square 4 small green squares 2 white rectangles 21 Shape prerequisite review // 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); } 22 Square prerequisite review // 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); } } 23 Rectangle prerequisite review // 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); } } 24 ViewPoly prerequisite review // 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]; ... } public void paint(Graphics g) { for(int i = 0; i < count; i++) scene[i].draw(g); } public static void Main (String [] args) { ViewPoly vp = new ViewPoly("Polymorphic Draw", 400, 400, 10); ... } } 25 prerequisite review ViewPoly diagram // In ViewPoly.java public void paint(Graphics g) { for(int i = 0; i < count; i++) scene[i].draw(g); Shape Shape Shape Shape Shape Shape Shape Shape } Square draw(g) : void Rectangle draw(g) : void Square draw(g) : void Square Rectangle draw(g) : void draw(g) : void 26 Rectangle’s members prerequisite review Rectangle Rectangle is-a Square Rectangle is-a Shape Square is-a Shape Rectangles and Squares can be contained by collections (arrays) that hold Shapes Square x Shape y color Shape (int, int, Color) side1 Square (int, int, Color, int) side2 Rectangle(int, int, Color, int, int) 27 prerequisite review Recursion 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); } } ")"); Welcome to DrJava. Working directory is ... > RecursiveFac rf = new RecursiveFac(); > System.out.println(rf.fac(4)); fac(4) fac(3) fac(2) fac(1) 24 recursive descent recursive ascent halting state call return fac(4) 24 = 4 * 6 fac(3) 6 =3*2 fac(2) 2 =2*1 fac(1) 1 28 Binary Search prerequisite review 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 + "]"); } 29 found(...) prerequisite review 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); }} Welcome to DrJava. Working directory is ... > 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] > 30 prerequisite review Fibonacci number 𝐹𝑖𝑏 𝑛 = 1 𝐹𝑖𝑏 𝑛 − 1 + 𝐹𝑖𝑏(𝑛 − 2) 𝑤ℎ𝑒𝑛 𝑛 ≤ 2 𝑤ℎ𝑒𝑛 𝑛 > 2 Write a java program to compute the Fibonacci number for "n" for example Fib(3) = 2 or fib(2) 1 Fib(4) = 3 or fib(3) fib(2) + fib(1) 1 + 1 Fib(6) = 8 or Fib(10) = 55 fib(5) fib(4) + fib(3) 3 + 2 + + + + + fib(1) 1 + + fib(2) 1 fib(4) fib(3) + fib(2) 2 + 1 31 prerequisite review Performance 32 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 worst case average case 1 n n/2 first cell has search value last cell has search value 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 worst case average case 1 log(n,2) log(n,2) -1 best middle cell has search value last cell searched this is half the worst case searches average worst n linear binary linear binary linear binary 16 1 1 8 3 16 4 64 1 1 32 5 64 6 Java Programs and Classes prerequisite review 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. 33 Classes and Methods prerequisite review 34 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. Design prerequisite review 35 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 Transparency prerequisite review 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. 36 HTML – web pages prerequisite review 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> View source for Comp282 page </html> 37 prerequisite review 38 Javadoc Javadoc is tool (program) that reads a java source file and generates online 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 jar files prerequisite review 39 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: • the only archive format that is cross-platform • the only 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 Purpose jar cf file.jar inputFile(s) jar tf file.jar jar xf file.jar create file.jar view files extract files