Java Notes

Share Embed Donate


Short Description

Download Java Notes...

Description

AP Lesson Notes – “A” Curriculum Lesson A1: Intro to OOP o Some important words to understand: object-oriented programming (OOP), object, attributes, behaviors, constructors, class, methods o An example of a Java class o Creating your first AP Java Project o Notes on compiling and running Java programs – and more vocabulary Lesson A2: Object-Oriented Programming o Our First Java Application o Program Components: comments, import statements, method o Object Declaration, Creation, and Message Sending o Class Diagrams o The Difference Between Objects and Classes Lesson A3: Primitive Data Types o Identifiers in Java o Primitive Data Types in Java: byte, short, int, long, float, double, char, and Boolean o Declaring and Initializing Variables in Java o Printing Variables Using the System.out Object o Assignment Statements o Math Operators + - * / % casting o Precedence of Math Operators o Assignment Operators = += -= *= /= %= o Increment and Decrement Operators ++ -Lesson A4: Object Behavior o Writing Methods in Java o Parameters and Arguments o Returning Values o The Signature of a Method o Lifetime, Initialization, and Scope of Variables o Getters/Setters Lesson A5: Designing and Using Classes o Designing a Class o Implementation of a Class o Determining Object Behavior o Instance Variables o Implementing Methods o Constructors o Using Classes

Lesson A6: Libraries and APIs o Understanding APIs o Final and Static o DrawingTool o Point2D.Double o Random o Math o Javadoc Tool Lesson A7: Simple IO o Reading Input with Scanner Class o Multiple Line Stream Output Expressions o Formatting Output Lesson A8: Control Structures o Structured Programming o Control Structures o Algorithm Development and Pseudocode o Relational Operators o Logical Operators o Precedence and Associativity of Operators o if-else Statements o Compound Statements o Nested if-else Statements o Boolean Identifiers o Switch Statements (optional) Lesson A9: Recursion o Recursion o Pitfalls of Recursion Lesson A10: Strings o String Class o String Constructors o Object References o null Value o String Query Methods o String Translation Methods o Immutability of Strings o Comparing Strings o Strings and Characters o toString method o String I/O Lesson A11: Inheritance o Single Inheritance o Class Hierarchies o Using Inheritance o Method Overriding o Interfaces

9/7/2009

Lesson A12: Iterations o while Loop o Loop Boundaries o Conditional Loop Strategies o for Loop o Nested Loops o The do-while Loop (optional) o Loop Invariants

Lesson A17: Quadratic Sorting Algorithms o Sorting Template Program o Bubble Sort o Selection Sort o Insertion Sort o Counting Steps - Quadratic Algorithms o Animated Sort Simulations o Sorting Objects

Lesson A13: Exceptions and File IO o Exceptions o Handling Exceptions o Exception Messages o Throwing Exceptions o Reading From a File o Writing to a File

Lesson A18: Merge and MergeSort o Non-Recursive MergeSort o A Merge Algorithm o Recursive MergeSort o Order of Recursive MergeSort

Lesson A14: Boolean Algebra and Loop Boundaries o Negations of Boolean Assertions o Boolean Algebra and DeMorgan's Laws o Application of DeMorgan's Laws Lesson A15: ArrayList o ArrayList Implementation of a List o ArrayList Class o Object Casts o Wrapper Classes o Iterator Lesson A16: Single Dimension Arrays o Example of an Array o Array Declarations and Memory Allocation o Application of Arrays o Arrays as Parameters o Arrays and Algorithms

Lesson A19: Sequential and Binary Searches o Sequential Search o Binary Search o Recursive vs. Non-recursive Algorithms Lesson A20: Inheritance, Polymorphism, and Abstract Classes o Inheritance o Abstract Classes o Polymorphism o Interfaces Lesson A21: Number Systems o Introduction to Number Systems o Review Decimal o Octal o Hexadecimal o Binary o Short Cuts Between Binary, Octal, and Hexadecimal o How this Relates to Computers and Overflow Errors Lesson A22: General Computer Knowledge o Hardware o Software o Networking o Ethics

9/7/2009

Lesson A1 notes: Intro to OOP Some important words to understand object-oriented programming (OOP) o programs consist of a collection of interacting objects o each object in a program has a job to do. object (i.e., a pencil or a piece if paper) o attributes: aspects of an object that describe it (i.e., a pencil‟s color, width, location, etc.) o behaviors: things the object can do (i.e., draw line, draw circle, move to new location, etc.) o constructors: create a new object and determine its initial attributes class o a definition for a type of object, like the blueprint for a type of house o defines the object‟s attributes, behaviors, and constructors o while a program is running, we create objects from class definitions to accomplish tasks methods o to tell an object to perform a task, we send a message to it…in Java, these messages are called methods o an object can only receive a message that it understands, so each type of message must be defined within the class definition o examples of some methods for the DrawingTool class which is provided by this curriculum o create a new object named “myPencil”…we say the object myPencil is an instance of the DrawingTool class…an object can only be an instance of one class o to draw a line of a specified length, we call the method “forward” and pass (i.e., communicate) the distance to move the pencil…a value we pass to an object‟s method is called an argument o if we need to change the direction myPencil is facing, we can call the “turnLeft” method, which will cause a ninety-degree turn to the left…we do not need to pass any arguments with the turnLeft method o we can use the “getColor” method to return the value…this method responds to user o wherever possible, reuse an existing class to create objects instead of writing code for a new class An example of a Java class o here is an example of a Java class which uses the pre-existing DrawingTool class for the pencil object and SketchPad class for the paper object o note, this code does not do anything by itself…later we will learn how to utilize this code in an actual program

9/7/2009

/* DrawSquare: this class will create a piece of paper and a pencil, place the pencil on the paper, and then draw a square. */ import gpdraw.*; public class DrawSquare { private DrawingTool pencil; private SketchPad paper; public DrawSquare() // the constructor { paper = new SketchPad(300, 300); pencil = new DrawingTool(paper); } public void draw() { // draw the square pencil.forward(100); pencil.turnLeft(90); pencil.forward(100); pencil.turnLeft(90); pencil.forward(100); pencil.turnLeft(90); pencil.forward(100); } }

o some notes about the above Java class o the DrawSquare object includes one DrawingTool object and one SketchPad object o the constructor is a method with the same name as the class  first instruction constructs new SketchPad object named “paper” with dimensions of 300 x 300  next instruction constructs new DrawingTool object named “pencil” using SketchPad object named “paper” o an object‟s behavior is determined by instructions within its methods…when the method draw() is called:  the instructions within the draw method will execute in the order they appear  there are seven instructions in draw method  first instruction will cause the “pencil” to move forward 100 units drawing a line as it goes  next instruction tells “pencil” to turn left  remaining five instruction repeat this process to draw remaining three sides of square. o the DrawSquare example illustrates the tools that a programmer uses to write a program o a program is built from objects and classes that a programmer writes or reuses o classes are built from instructions o these instructions manipulate objects to perform the desired tasks Creating your first AP Java Project [we will do this together] 9/7/2009

o start BlueJ o create new project o Project –> New Project…select a location on your X-drive and enter “\myFirstProject” to create a folder for your new project o create new class named “Main” o New Class -> enter “Main” as the class name -> click “OK” o double click on main o enter the following code (to replace the code for “Main” which is already there): public class Main { public Main() { } public static void main(String[] args) { System.out.println("Starting my first AP Java program."); DrawHouse house1 = new DrawHouse(); house1.draw(); System.out.println("Finishing my first AP Java program."); } }

o o o o o o o o o o o

click “Close” add “DrawHouse” class to your project Edit -> Add class from file select java file “DrawHouse.java” from “C:/stuff for BHS programming students/ first AP Java project” on your C-drive click “Add” compile and run your program click “Compile” right-click “Main” click “void main(String[] args)” click “OK” a square should appear in a window called “Drawing Tool”

Notes on compiling and running Java programs – and more vocabulary o a programmer writes the text of a program using a software program called an editor o the text of a program in a particular programming language is referred to as source code o the source code is stored in a file called the source file…for the first example, source code would be saved in a file named “DrawSquare.java” o the Java compiler converts source code written in Java into the bytecode language the Java interpreter understands…for the first example, the Java compiler will create a bytecode file named “DrawSquare.class” o errors detected by the compiler are called compilation errors…usually violation of various Java language syntax rules that programmers must follow

9/7/2009

o when you run a Java program, the Java interpreter processes the bytecode file and executes the instructions in it. o if an error occurs while running the program, the interpreter will catch it and stop its execution…such errors detected by the interpreter are called run-time errors

Lesson A2 notes: Object-Oriented Programming Our First Java Application o in lesson 1 we encountered a Java program called the DrawSquare class o includes following two methods  DrawSquare(): named exactly the same as the class…used to construct new instances of this class…calls SketchPad‟s constructor to create a new SketchPad object named myPaper with an initial size of 300 by 300 pixels… calls DrawingTool constructor to create a new DrawingTool object named myPencil  draw(): where most of action for this class takes place for actual drawing of square o we create what is called a driver or throwaway class for the purpose of testing DrawSquare. public class driverClass { public static void main(String[] args) { DrawSquare sq = new DrawSquare(); sq.draw(); } }

Program Components o comments  helps programmer and other readers understand what is going on…not part of actual code  three types /* Multi-line comment For longer documentation notes */ // Single-line comment which starts at the slashes // and stops at the end of the line /**

Java-doc comment…a special type of comment we will discuss later

*/

o import statement to allow program to use predefined classes written by others so programmer does not have to "reinvent the wheel"… in Java, these predefined classes are grouped into packages…some come with Java and some are written by other programmers… the package we have been using so far is called gpdraw which includes the DrawingTool and SketchPad classes…they are imported using the statement: import gpdraw.*;

9/7/2009

o the driver class includes a main method o most classes contain methods to define a class‟s behavior…a method has the following general syntax: modifiers return_type method_name ( parameters ) { method_body }

o modifiers define access to methods (e.g. public, private) o method_name is name of the method (e.g. draw) o return_type refers to the type of data a method returns, either one of predefined types (e.g., int, double, char, String, etc.) or a user-defined class or void if method does not return a value o parameters list allows us to send values to a method (e.g. 100) o method_body contains statements to accomplish the work of the method

Object Declaration, Creation, and Message Sending o every object in a program must be declared using following syntax class_name object_name

o class_name is name of class to which objects belong o object_name is sequence of object names separated by commas o examples DrawingTool myPencil; Customer bob, betty, bill;

o no objects are actually created (or instantiated) by the declaration…calling a constructor using the following syntax creates an object: object_name = new class_name ( arguments ) ;

o o o o

object_name is name of declared object class_name is name of class to which object belongs arguments is a sequence of zero or more values passed to the constructor example myPaper = new SketchPad(300, 300);

o after object is created, we can start sending messages to it using the following syntax: object_name.method_name( arguments ) ;

o o o o

object_name is name of declared object method_name is name of method of object. arguments is a sequence of zero or more values passed to method. example myPencil.forward(100);

9/7/2009

Class Diagrams o pictures are often helpful when designing software, such as the class diagram Class Name: DrawSquare Attributes: SketchPad DrawinfTool Methods: DrawSquare() draw() o an attribute, or instance variable, represents a property of an object o a method is an operation that can be performed upon an object o this diagram is part of the Unified Modeling Language (UML), the most widely used set of notations in today‟s software engineering industry o “...” notation can be shown in a class diagram to indicate list of methods is incomplete o class diagrams frequently include labels within “>” symbols to categorize class methods (e.g. >, >) The Difference Between Objects and Classes o a class: o o o o

a blueprint that defines attributes and methods. written by a programmer.

o o o o

is an instance of that class. exists during the time that a program executes must be explicitly declared and constructed by the executing program has attributes that can change in value and methods that can execute during program execution. (The class to which the object belongs defines theses attributes and methods.) is most often referenced using an identifier.

cannot be altered during program execution. named by a class name. o an object: o must belong to some class.

o

Lesson A3 notes: Primitive Data Types Introduction o Java allows two different types of attributes: objects and primitive data types Identifiers in Java o an identifier is a name that will be used to describe classes, methods, constants, variables; anything a programmer is required to define 9/7/2009

o

o o o

rules for naming identifiers in Java: o must begin with a letter. o only letters, digits, or an underscore may follow the letter. o the blank space cannot be used Identifiers o cannot be reserved words already defined in Java such as new, class, etc. Java is a case sensitive language, so grade and Grade are different identifiers a good identifier should help describe the nature or purpose of whatever it is naming the following conventions are used throughout ICT curriculum guide o single word identifier will be written in lower case only: grade o class names will begin with upper case: DrawingTool o if an identifier is made up of several words, all words beyond the first will begin with upper case: passingScore, DrawHouse o identifiers used as constants will be fully capitalized: PI

Primitive Data Types in Java o

o o o o

Java provides eight primitive data types: byte, short, int, long, float, double, char, and Boolean o byte, short, int, and long are for integers o float and double are for real numbers (numbers with decimal places) o AP Exam only requires you to know int, double, and boolean o this curriculum will, from time to time, also use the char type when appropriate. int: integer…any positive or negative number without a decimal point…7…-23 double: signed or unsigned number with a decimal point, but no commas… 7.5…66.72…5…scientific notation such as 1.625e3 or 1.25e-4 see lesson for bytes allocated as well as minimum and maximum values for each data type char: characters o letters, digits 0 through 9, and punctuation symbols o enclosed within single quotes such as 'A', 'a', '8', '*' o stored as integers using ASCII (American Standard Code for Information Interchange) codes…for example, ‟A‟ is stored as the number 65 and „K‟ as 75, so: char letter = 'A'; int number = 75; System.out.println(letter); // prints “A” System.out.println((int)letter); // prints “65” System.out.println((char)number); // prints “K”

 o

o

note, the use of “(int)” is called casting…data type of variable is

converted to type in parentheses temporarily Java provides escape sequences for using unusual keystrokes on the keyboard such as Newline („\n‟), Horizontal tab („\t‟), Backslash („\\‟), Single quote („\‟‟), Double quote („\”‟) and Null character („\0‟) in a String literal, such as in a System.out.println statement

boolean: used to represent a single true/false value…ccan have only one of two values: true or false

Declaring and Initializing Variables in Java o

a variable must be declared before it can be initialized with a value, using following syntax data_type

variableName;

9/7/2009

o

examples: int number = 4; // declared and initialized in one line char ch; // just declared int first = 5, second; // multiple variables declared on one line double x; boolean done; int sum = first + second;

o

variables can be declared in a class outside of any methods or inside of a method

Printing Variables Using the System.out Object o o o

the System.out object is automatically created in every Java program it has methods for displaying text strings and numbers in plain text format on the system display, which is sometimes referred to as the “console.” examples: int number = 5; System.out.println("number = " + number); // displays number = 5 char letter = 'E'; System.out.println("letter = " + letter); double average = 3.95; System.out.println("average = " + average); boolean done = false; System.out.println("done = " + done); // displays done = false System.out.print("The "); // does not skip to next line System.out.println( 2 + 2); // Output: 4 System.out.println(“2 + 2”); //Output: 2 + 2 System.out.println(“2” + “2”); //Output: 22

o

first System.out.println uses + operator to “add” a string (the literal "number = ") and number (the int variable containing the number 5)…Java defines a version of the + operator for String concatenation that enables a string and a value of another data type to be concatenated (added)…result is new (and normally longer) String

Assignment Statements o an assignment statement has the following basic syntax: variable = expression;

o assignment operator (=) assigns the value of the expression on the right to the variable and returns the value of the expression

o examples a = 5; b = 6 * a; a = b = 5; primitiveValue = 18234; myPencil = new DrawingTool();

o primitiveValue is a primitive type, so assignment statement puts data directly into it, replacing previous value

9/7/2009

o myPencil is an object reference variable (the only other possibility) so a reference to object is put into that variable, replacing previous reference…object reference tells program where to find an object…a variable will never actually contain an object, only a reference to an object

Math Operators o

Java provides 5 math operators as listed below: + * / %

o

o

Addition, as well as unary + Subtraction, as well as unary Multiplication Floating point and integer division Modulus, remainder of integer or floating point division

numerical result and data type of answer depends on type of operands used o if both operands are integers, result is an integer: 2 + 3 -> 5...11/2 -> 5 o If either of operands is a double type, result is a double: 25 / 6.75 -> 3.7037…the integer is promoted to a double value, and then the math is executed modulus operator (%) returns the remainder of dividing the first operand by the second: 10 % 3 -> 1…27.475 % 7.22 -> 5.815

o o

changing the sign of a value can be accomplished with negation operator (-), often called unary (-) operator. A unary operator works with only one value to obtain answer of 5.5 to a question like 11/2, must cast one of operands using following syntax: (type) operand...such as (double)11/2

Precedence of Math Operators o

precedence rules govern the order in which an expression is solved Level of Precedence

Operator

Associativity

Highest

unary * / % + -

right to left left to right left to right

Lowest o o o

for example 2 + 3 * 6 -> 20 since * operator has priority over + associativity refers to order in which operators are applied if they have same precedence level. The two possibilities are from left-to-right or right-to-left parentheses take priority over all the math operators so (5+6)/(9-7) -> 11/2 -> 5

Assignment Operators o o o o

the statement “number = number + 5;” is an example of an accumulation statement. The old value of number is incremented by 5 and the new value is stored in number. above statement can be replaced as follows: number += 5; Java provides the following assignment operators: += -= *= /= %= precedence of the assignment operators is the lowest of all operators

Increment and Decrement Operators o o o

incrementing or decrementing by one is a common task in programs can be accomplished by the statements: “n = n + 1;” or “n += 1;” or “n++” or “++n” Java also provides for a decrement operator, --, which decrements a value by one

9/7/2009

o o

statement “b = ++a” uses pre-increment operator to increment value of a and return new value of a statement “b = a++” uses post-increment operator to return value of a and then increment a by 1

Summary o

at first it is necessary to memorize the above syntax of data types and their operations, but, with time and practice, fluency will come

Lesson A4 notes: Object Behavior Introduction o o o

programs of any significant size should be broken down into smaller pieces classes can be used to create objects that will solve those smaller pieces we determine what behaviors these objects will perform; these behaviors are called methods

Writing Methods in Java o o o

methods are what an object can actually do, such as “myPencil.forward(100);” in our DrawingTool example we wrote our own methods (DrawSquare, draw) and we used methods from the DrawingTool class (forward, turnLeft) remember the general syntax of a method from lesson 2

Parameters and Arguments o o

parameters and arguments are used to pass information to a method arguments are used when calling the method o for example, in “myPencil.forward(100);” we tell the forward method how far to move by passing an argument to it: int value 100 o turnLeft method will default to 90 degrees if we don‟t pass it a value…if we want it to turn a different amount, we can send how far left we want it to turn in degrees such as by saying “myPencil.turnLeft(60);” o arguments can be either literal values (2, 3.5) or variables (a, x) //These are equivalent calls double db4 = doMath(5, 10); // example using literal values int a = 5; int x = 10; double db5 = doMath(a, x); // example using variables

o

parameters are used when defining a method o when defining a method, the list of parameters can contain multiple parameters: o for example public double doMath(int a, double x) { ... code ... return doubleVal; }

9/7/2009



when this method is called, arguments fed to doMath method must be correct type and in same order. First argument must be int. Second argument can be double or int (since int will automatically be converted by Java) double dbl = doMath(2, 3.5); double db2 = doMath(2, 3); double db3 = doMath(1.05, 6.37);

o

// // //

this is okay this is okay this will not compile

when method is called with an argument, parameter receives value of argument  if data type is primitive, we can change value of parameter within method as much as we want and not change value of argument passed in method call  object variables, however, are references to object‟s physical location. Therefore, when we use reference to access object within method, we have ability to directly change the object. This can get very messy if the programmer doesn‟t realize what is going on

Returning Values o o o

sometimes we want a method to return a value in order for a method to return a value, there must be a return statement somewhere in body of method. you must also declare which type of data value will be returned in the method declaration. This can be any primitive data type, a Java class, or any class that you have defined yourself. public int getNumber() { int myNumber = 1234; return myNumber; }

o

if a method returns no value, the keyword void should be used. For example: public void printHello() { System.out.println("Hello world"); }

The Signature of a Method o

in order to call a method legally, you need to know its name, how many parameters it has, the type of each parameter, and the order of those parameters. This information is called the method's signature. The signature of the method doMath can be expressed as: doMath(int, double)

o o

signature does not include names of parameters; if you want to use method, you don't need to know what parameter names are

Java allows two different methods in same class to have same name, provided their signatures are different. We say that name of the method is overloaded because it has different meanings. The Java compiler can tell which one you want to call by the number and types of arguments that you provide in call statement. For example with DrawingTool class turnLeft() turnLeft(120)

9/7/2009

o

it is illegal to have two methods in same class that have same signature but different return types. For example: double doMath(int a, double x){} int doMath(int a, double x){}

Lifetime, Initialization, and Scope of Variables o o

o

o

three categories of Java variables have been explained thus far in these lessons. instance variables, local variables, and parameters lifetime of a variable defines portion of runtime during which variable exists o when an object is constructed, all its instance variables are created. As long as any part of program can access object, it stays alive o a local variable is created when program executes statement that defines it. It stays alive until block that encloses variable definition is exited o when a method is called, its parameters are created. They stay alive until method returns to caller type of variable determines its initial state o instance variables are automatically initialized with a default value (0 for numbers, false for boolean, null for objects) o parameters are initialized with copies of arguments o local variables are not initialized by default so an initial value must be supplied by the programmer. The compiler will generate an error if an attempt is made to use a local variable that may not have been initialized. scope refers to area of program in which an identifier is valid and has meaning o instance variables are usually declared private and have class scope. Class scope begins at the opening left brace ({) of the class definition and terminates at the closing brace (}). Class scope enables methods to directly access all of its instance variables o scope of a local variable extends from the point of its definition to the end of the enclosing block o scope of a parameter is the entire body of its method

Getters/Setters o o

o

when you are first starting to program, some of the most commonly used methods are called Getters and Setters Getter methods o purpose is to provide others with current information about an object‟s attributes o example: a “double getLength()” method which returns value of object‟s “length” attribute o storing “length” in a private instance variable prevents others from accessing length directly, because they might alter that data when we don‟t want them to o also called Accessors Setter methods o purpose is to allow others to change an object‟s attributes o example: a “void setLength(double d)” method which changes value of object‟s “length” attribute o often Setter methods are given a return type of boolean which will return true if the value was valid and false if the value was not. This lets clients know if their value was accepted or not. o also called Mutators or Modifiers

9/7/2009

Lesson A5 notes: Designing and Using Classes Designing a Class o one of advantages of object-oriented design is that it allows a programmer to create a new data type that is reusable in other situations

o when designing a new class, three components must be identified – attributes, behaviors, and constructors. Let‟s consider a checking account at a bank o the account would need to record such things as the account number, the current balance, the type of checking account it is, etc (these are nouns). These would be the attributes of the checking account o it would also need to be able to do certain actions, such as withdrawing or depositing money (these are verbs). These would be the behaviors of the checking account o finally, the checking account object needs to be created in order to be used, so the class must define how the creation process works. This is accomplished in the constructors.

Implementation of a Class o a possible implementation of such a CheckingAccount class is given below public class CheckingAccount { private double myBalance; private int myAccountNumber; public CheckingAccount() { myBalance = 0.0; myAccountNumber = 0; } public CheckingAccount(double initialBalance, int acctNum) { myBalance = initialBalance; myAccountNumber = acctNum; } public double getBalance() { return myBalance; } public void deposit(double amount) { myBalance += amount; } public void withdraw( double amount ) { myBalance -= amount; } }

Determining Object Behavior

9/7/2009

o

o

before you start programming, you need to understand how the objects of your class behave. Possible behaviors for a checking account could be  accepting a deposit  withdrawing from the account  getting the current balance in Java, these behaviors are expressed as method calls such as the following: checking.deposit(1000); checking.withdraw(250); System.out.println("Balance: " + checking.getBalance());

o o o

to the calling program, an object of type CheckingAccount can be viewed as a “black box” that can carry out its methods. The programming concept of not needing to know how things are done internally is called abstraction once we understand what objects of the CheckingAccount class need to do, it is possible to design a Java class that implements these behaviors. To describe object behavior, you first need to implement a class and then implement methods within that class we could start by writing the following public class CheckingAccount { // CheckingAccount data // CheckingAccount constructors // CheckingAccount methods }

o

next we add the three methods public class CheckingAccount{ // CheckingAccount data // CheckingAccount constructors public void // method } public void // method }

deposit( double amount ){ implementation withdraw( double amount ){ implementation

public double getBalance(){ // method implementation } }

o o

what we have been doing here is not real code and wouldn‟t actually do anything. However, it is useful to lay out what your class will look like. When we use a mixture of English and Java to show what we are doing, it is called pseudocode next we can write out what methods will do with pseudocode so that it becomes easier to see how everything will fit together. This process of starting with a very broad concept or outline and working down to smaller and smaller details is called top-down design public class CheckingAccount {

9/7/2009

// CheckingAccount data // CheckingAccount constructors public void deposit( double amount ) { // receive amount of deposit and add it to current balance } public void withdraw( double amount ) { // remove amount of withdrawal from current balance } public double getBalance() { // return current balance in a double value } }

o

a method header consists of the following parts access_specifier return_type

method_name ( parameters )

o access_specifier controls where this method can be accessed from  “public” if method needs to be accessed by other objects  “private” if it should only be accessed within this object o return_type is data type that method sends back  examples: int, double or DrawingTool  can be any primitive type or any object that your class knows about  void if method does not return a value o o

method_name needs to follow rules of identifiers and should indicate method‟s

purpose. list of parameters of the method such as “double amount”  parameters are the input to the method  the deposit and withdraw methods each have one parameter, the amount of money to deposit or withdraw  type of parameter, such as double, and name for each parameter, such as amount, must be specified  if a method has no parameters, like getBalance, it is still necessary to supply a pair of parentheses () behind the method name.

Instance Variables o o o

before any code can be written for behaviors, object must know how to store its current state state is set of attributes that describes object and influences how object reacts to method calls. For checking account objects, state includes current balance and an account identifier. each object stores its state in one or more instance variables. public class CheckingAccount { private double myBalance; // instance variable private int myAccountNumber; // instance variable // CheckingAccount constructors

9/7/2009

// CheckingAccount methods }

o

an instance variable declaration consists of following parts: access_specifier type variable_name

o

access_specifier tells who can access that data member…generally declared with access specifier private so they can be accessed only by methods of same

class o o o

type of variable (such as double). variable_name

if instance variables are declared private, then all external data access must occur through the non-private methods. This means that instance variables are hidden. The process of hiding data is called encapsulation. For example, because myBalance instance variable is private, it cannot be accessed from outside of the class, so: double balance = checking.myBalance;

o

// would generate compiler ERROR!

however, the public getBalance method can be called to inquire about the balance: double balance = checking.getBalance();

// OK

Implementing Methods o

once method header has been specified, implementation of method must be supplied in a block that is delimited by braces {...} public void deposit(double amount){ myBalance += amount; }

o

syntax of a return statement is: return expression; or return;

// Exits the method without sending back a value

Constructors o

final requirement to implement a class is to define one or more constructors, whose purpose is to initialize values of instance variables of an object, such as public CheckingAccount() { myBalance = 0.0; myAccountNumber = 0; } o o o

constructors always have same name as their class similar to methods, constructors are generally declared as public to enable any code in another program to construct new objects of the class unlike methods, constructors do not have return types

9/7/2009

o

many classes define more than one constructor through overloading, such as public CheckingAccount(double initialBalance, int acctNum) { myBalance = initialBalance; myAccountNumber = acctNum; }

o

using constructors o to construct objects of class, first it is necessary to declare an object variable, such as CheckingAccount checking; object

o

// object‟s reference, the address of

new operator allocates memory for object, returning reference to newly constructed

object. checking = new CheckingAccount();

o

// to create object

in most cases, declare and store reference to object on one line as follows: CheckingAccount checking = new CheckingAccount();

o

occasionally, it would be repetitive and unnecessary to create an object identifier: DrawingTool pen = new DrawingTool(new SketchPad(500,500));

o

notice that we never create an object identifier for the SketchPad object

Using Classes o

o

using the CheckingAccount class is best demonstrated by writing a program that solves a specific problem. We want to study the following scenario: an interest-bearing checking account is created with a balance of $1,000. For two years in a row, add 2.5% interest. How much money is in the account after two years? two classes are required o CheckingAccount class that was developed above o second class called CheckingTester. Main method of CheckingTester class constructs a CheckingAccount object, adds interest twice, then prints out balance class CheckingTester { public static void main(String[] args) { CheckingAccount checking = new CheckingAccount(1000.0, 123); double INTEREST_RATE = 2.5; double interest; interest = checking.getBalance() * INTEREST_RATE / 100; checking.deposit(interest); System.out.println("Balance after year 1 is $" + checking.getBalance()); interest = checking.getBalance() * INTEREST_RATE / 100; checking.deposit(interest); System.out.println("Balance after year 2 is $" + checking.getBalance()); }

9/7/2009

}

Lesson A6 notes: Libraries and APIs Introduction o huge number of pre-made classes provided with Java o as a Java programmer, you want to avoid redoing work already done o this lesson covers o how to read the APIs that come with those classes, and o how to write our own APIs so that other people can use our classes Understanding APIs o o o o o

o

API stands for Application Programming Interface APIs show exactly how to use pre-made classes lists classes and constructors…tells us what methods we can access, how to interact with those methods, and what those methods will return back to us. does not tell us how class eas designed and programmed can access Java APIs on Web at java.sun.com…click on API Specifications on main page, then choose version of Java…can also download APIs to your computer for offline access…organized both by package and by class (packages are groups of related classes that are “packaged” together) when you use the code “import gpdraw.*;”, you are adding the entire gpdraw package to your code…if you only need a few classes from a package, you can add classes individually with the code “import gpdraw.DrawingTool;”

Final and Static o o

o

keywords final and static frequently come up in API documentation final o when used with a primitive data type, final means that value of variable will never change o useful in many cases, such as tax rates and math constants such as PI o identifiers with final are generally made with only capital letters so they are easily distinguishable from rest of code o example: final double TAXRATE = 0.0825; o you can initialize the value when the variable is declared or determine it at run time, but once a final variable is given a value within a program, that value may never change in that run o using final values makes program easier to modify and reduces errors static o using keyword static means that data member or method is attached to class rather than to an object of class o with a static method, you only need to type name of class followed by the name of method, such as “int jason = Math.pow(3,4);” o similar for a static data member…if one object changes value of a static variable, then value is changed for all other objects of that type o you never need to create a new object when dealing with static methods or data members

DrawingTool 9/7/2009

o o

for DrawingTool, Handout A1.1 gives an introduction to purpose of class and how to use its various methods: name of method, type of arguments it takes, and what will happen after method is called it was not the official Java format for an API, but it accomplished same thing

Point2D.Double o o

Point2D class is useful for storing locations on a two dimensional space whenever possible we want to avoid writing code that has already been written, so do a little research to see if someone else has written code you can use

Random o o

java.util package is full of utility classes that you will find very useful java.util.Random is one of them…here is some information from its Javadoc…the word “pseudorandom” just indicates that the number is not completely random

Constructor Summary Random()

Creates a new random number generator.

Method Summary double nextDouble()

Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence. int nextInt(int n)

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. o

here is an example of some code: Random chooser = new Random();

int winner = chooser.nextInt(200) + 1; Math o Math class in the java.lang package contains class methods for commonly used mathematical functions

o Java loads the java.lang package automatically, so no special actions are required to access these

o here is some information from its Javadoc java.lang

Class Math java.lang.Object java.lang.Math public final class Math extends Object

9/7/2009

Field Summary static double E The double value that is closer than any other to e, the base of the natural logarithms. static double PI The double value that is closer than any other to pi, the ratio of the circumference of a circle to its diameter.

Method Summary static double abs(double a) Returns the absolute value of a double value. static int abs(int a) Returns the absolute value of an int value. static double pow(double a, double b) Returns the value of the first argument raised to the power of the second argument. static double sqrt(double a) Returns the correctly rounded positive square root of a double value.

o there are over 30 other methods such as Math.sin…you can access them by going to java.sun.com, clicking on API‟s, selecting a version of Java such as J2SE 1.5.0, and selecting the Math class within the Java.lang package o here is an example using the Math class: Math.abs(-25)

Javadoc Tool o basics of creating your own APIs are pretty simple o use tag /**…*/ before each class, variable, constructor, and method to create block comments o these comments work within your code in essentially same way as regular block comment tag /*…*/ however, when we run the Javadoc tool, APIs will be created based on these comments the first line of each comment should be a quick description rest of comment should consist of a more detailed description when you run “javadoc.exe” program on your Java class file (as discussed in Handout A6.1, Javadocs), it will create html files in local directory if you open up index.html with your Web browser, you will find yourself looking at an API created for your class

o o o o

Lesson A7 notes: Simple IO Introduction o

input and output is usually referred to as I/O

9/7/2009

o o

many different ways a Java program can perform I/O…this lesson covers some very simple ways Advanced Placement subset does not require that you know how to use any specific input and output classes, only that you know how to use I/O in some manner

Reading Input with Scanner Class o o o o

o

some programs from preceding lessons have been written without any flexibility…to change data values in programs, it is necessary to change variable initializations, recompile program, and run it again sometimes prompting user for a value is more efficient and convenient accepting user input in Java can be complex…we will use Scanner class to make processing input easier just as System class provides System.out for output, there is an object for input, System.in; it does not directly support convenient methods for reading numbers and strings, so Scanner class sits between System.in object and our program Scanner is part of java.util package, so we need to start off by adding Scanner class to our import section. import java.util.Scanner;

o

next, we create a Scanner object and pass System.in object to it Scanner in = new Scanner(System.in);

o o

this tells Scanner to look at System.in object for all of its input (in Lesson A13, Exceptions and File I/O, we will learn how to change object we pass to Scanner so we can read data stored in text files) here are some examples: int num1; num1 = in.nextInt( );

// program pauses until an appropriate value is entered on keyboard double bigNum; bigNum = in.nextDouble( ); boolean isTrue; isTrue = in.nextBoolean( );

o o

whitespace (spaces, tabs, newline) separates input values…when reading values, whitespace keystrokes are ignored when requesting data from user via keyboard, it is good programming practice to provide a prompt such as: System.out.print("Enter an integer -->

");

Multiple Line Stream Output Expressions o

when length of an output statement exceeds one line of code, it can be broken up in several different ways: System.out.println("The sum of " + num1 + " and " + num2 + " = " + (num1 + num2));

9/7/2009

or System.out.print("The sum of " + num1 + " and " + num2); System.out.println( " = " + (num1 + num2)); but not System.out.print("A long string constant must be broken up into two separate quotes. This will NOT work.");

Formatting Output o o

to format, use printf()…it works similarly to print() and println() methods printf() method takes two arguments…first is formatting String, a special sequence of characters that tells printf() how to display second argument…syntax is: %[flags][width][.precision]conversion o o

„%‟ tells printf method that formatting is coming…all formatted String constants start with %...does not have to be first thing in String constant, just first part of any formatted text. most important conversion tags are „s‟, „d‟, and „f‟. Conversion Tag s d f

o

Usage Type String literals Ints Doubles

Example printf(“%s”, “Sam”) printf(“%d”, 5182) printf(“%f”, 2.123456)

precision…max # characters to print out when used with „s‟….# decimal places to print out, rounded to the closest number, when used with „f‟, with default to six places System.out.printf(“%.2s”, “Hello”) -> He System.out.printf(“%.10s”, “Hello”) -> Hello System.out.printf(“%.4f”, Math.PI) -> 3.1416 System.out.printf(“%f”, Math.PI) -> 3.141593

o

width: min # characters to print out…for creating right-aligned lists…“Prices:” and “Prices:\n” are two different sizes…for left-aligned, add „-„ to left of width value

System.out.printf(“%-10s”, “Name:”); System.out.printf(“%11s”, “Price:\n”); // 11 to adjust for /n error System.out.printf(“%-10s”, “Soda”); System.out.printf(“%10.2f”, 10.25); System.out.println(); // since numeric cannot use special characters System.out.printf(“%-10s”, “Candy”); System.out.printf(“%10.2f”, 1.50); Run Output: Name: Soda Candy

Price: 10.25 1.50

9/7/2009

o

flags: „+‟ for positive or negative sign…„(‟ cause negative numbers to be enclosed with parentheses…„,‟ add commas…to get a dollar sign before printed value, place „$‟ before „%‟ System.out.printf(“%,d”, 12345678) -> 12,345,678 System.out.printf(“$%,d”, 12345678) -> $12,345,678 System.out.printf(“%,(d”, -12345678) -> (12,345,678)

o

can put multiple arguments in one call to printf()…put multiple formatting Strings in first argument, then add additional arguments separated by commas. double mySum = 123.456 System.out.printf(“%10s %10.2f”, “Total:”, mySum);

o

this curriculum uses just a few of many things printf() is capable of…look at API for Formatter class for more information on formatting Strings.

Lesson A8 notes: Control Structures Introduction o most basic control structures are if, if-else, and switch statements Structured Programming o in early days of programming (1960's), the approach to writing software was relatively primitive and ineffective…much of code was written with goto statements that transferred program control to another line in the code…the term "spaghetti code" comes from trying to trace code linked together with goto statements o the complexity this added to code led to the development of structured programming: o no goto statements are to be used in writing code o all programs written in terms of three control structures: sequence, selection, iteration o each control structure has one entrance point and one exit point, except for multiple exit points from a control structure using break statement o control structures may be stacked (sequenced) one after the other. o control structures may be nested inside other control structures. o control structures of Java encourage structured programming…staying within guidelines of structured programming has led to great productivity gains in field of software engineering Control Structures o only three necessary control structures needed to write programs: sequence, selection, and iteration o sequence refers to line-by-line execution as used in your programs so far…program enters sequence, does each step, and exits sequence o selection allows choice among different paths…Java provides different levels of selection • one-way selection with an if structure • two-way selection with an if-else structure

9/7/2009

• multiple selection with a switch structure o iteration refers to looping…Java provides three loop structures discussed Lesson A12: • while loops • do-while loops • for loops Algorithm Development and Pseudocode o an algorithm is a solution to a problem such as "finding the average of two numbers" o major task is conversion of rough designs into refined algorithms that be coded in language of choice o Pseudocode refers to a rough-draft outline of an answer, written in English-like terms…generally uses phrases and words that are close to programming languages…translation into code occurs more easily than if skipped pseudocode stage o Stepwise refinement is the process of gradually developing a more detailed description of an algorithm Relational Operators o a relational operator compares two values…following symbols used in Java as relational operators: < > = == !=

o

less than greater than less than or equal to greater than or equal to equal to not equal to

example: number > 16

o o

grade == 'F'

passing >= 60

result of relational expression is boolean value of either true or false. when character data is compared, ASCII code values are used to determine answer 'A' < 'B' 'd' < 'a' 't' < 'X'

evaluates as true, (65 < 66) evaluates as false, (100 < 97) evaluates as false, (116 < 88) since upper case letters come first in

ASCII Logical Operators o three logical operators in AP subset are AND, OR, and NOT, represented by following symbols AND OR NOT

o

&& || (two vertical bars) !

&& (and) operator requires both operands (values) to be true for result to be true. (true (true (false (false

&& && && &&

true) -> true false) -> false true) -> false false) -> false

9/7/2009

((2 < 3) && (3.5 > 3.0)) -> true ((1 == 0) && (2 != 3)) -> false

o o

&& operator performs short-circuit evaluation in Java: if first operand in && statement

is false, operator immediately returns false without evaluating second half. || (or) operator requires only one operand (value) to be true for result to be true. (true (true (false (false

|| || || ||

true) -> true false) -> true true) -> true false) -> false

((2+3 < 10) || (19 > 21)) -> true

o o

|| operator also performs short-circuit evaluation in Java: if first half of ||

statement is true, operator immediately returns true without evaluating the second half ! operator is a unary operator that changes a boolean value to its opposite (! true == false) -> true !(2 < 3) -> false

Precedence and Associativity of Operators o abbreviated precedence chart:

o

Operator

Associativity

! * + < == && || =

right to left left to right left to right left to right left to right left to right left to right right to left

unary - ++ -/ % >= != (and) (or) += -= *= /=

parentheses not needed, but can be used to make complex expressions more readable ((2 + 3 < 10) && (75 % 12 != 12)) (2 + 3 < 10 && 75 % 12 != 12)

if-else

o

// easier to read // harder to read

Statements

general syntax of the if statement is as follows: if (expression) { statement1; }

o o

if expression evaluates to true, statement1 is executed…if expression is false, nothing is executed and program execution picks up after ending curly brace (}) following diagram shows flow of control:

9/7/2009

o

to provide for two-way selection, an if statement may add an else option. if (expression) { statement1; } else { statement2; }

o o

if expression evaluates to true, statement1 is executed…if false, statement2 would be executed following diagram shows flow of control

o

expression being tested must always be placed in parentheses

Compound Statements o statement executed in a control structure can be a block of statements, grouped together into a single compound statement o created by enclosing any number of single statements by braces as shown in following example: if (expression){ statement1; statement2; statement3; }else{ statement4; statement5;

9/7/2009

statement6; }

Nested if-else Statements o statement inside of if or else option can be another if-else statement o known as nested if-else constructions o example: if (expression1) { if (expression2) { statement1; } else { statement2; } } else { statement3; }

o o

braces need to be correct to ensure ifs and elses get paired with their partners above example has three possible different outcomes as shown in the following chart: expression 1 expression2 statement executed true true statement1 true false statement2 false not tested statement3

o o

braces not needed for if and if-else structures with only one statement, but safer to always use braces another alternative makes use of the && operator, which is slightly easier to read. if (expression1 && expression2) { statement1; }

o

example determining type of triangle given three sides A, B, and C. if ( (A == B) && (B == C) ) System.out.println("Equilateral triangle"); else if ( (A == B) || (B == C) || (A == C) ) System.out.println("Isosceles triangle"); else System.out.println("Scalene triangle");

Boolean Identifiers o can use boolean variables to write code that is easier to read such as Instead of if(done == true) { System.out.println("We are done!");

9/7/2009

} we can write if(done) { System.out.println("We are done!"); }

o

second version is less dangerous, because if you make a mistake and only put “=” instead of “= =”, Java will not catch that and interprets statement as assignment

Switch Statements (optional) o AP exam does not test on switch statement, but it is a very useful tool o general form of switch statement is: switch (expression) { case value1: statement1; statement2; ... break; case value2: statement3; statement4; ... break; case valuen: //any number of case statement may be used statement; statement; break; default: statement; statement; break; } // end of switch statement

o

flow of control of switch statement is illustrated below

9/7/2009

o o o o o

o

switch statement attempts to match value of expression with one of case values if match occurs, all statements past case value are executed until a break statement is

encountered break statement causes program control to jump to end of switch statement if break statement is omitted, all statements following matching case value are executed if it is possible that none of case statements will be true, can add default statement at end of switch…this will only execute if none of case statements are ctrue example for printing work day of week, where “day” is an integer variable switch (day) { case 1: System.out.println case 2: System.out.println case 3: System.out.println case 4: System.out.println case 5: System.out.println default: System.out.println }

o

("Monday"); break; ("Tuesday"); break; ("Wednesday"); break; ("Thursday"); break; ("Friday"); break; ("not a valid day"); break;

example using character variable if (('a' 0

Strings and Characters o natural to think of a char as a String of length 1 o in Java char and String types are incompatible since a String is an object and a char is a primitive type o extracting a char from within a String can be accomplished using charAt method o concatenating any char with an empty string (String of length zero) results in a string that consists of that char char myChar = „X‟; String myString = "" + myChar; System.out.println(myString); char anotherChar = „Y‟; myString += anotherChar; System.out.println(myString);

// X // XY

toString method o wouldn‟t it be nice to be able to output objects that you have made using simple line System.out.print(Object name), without having to do a lot of System.out.print statements

9/7/2009

o can create a toString method in any of your classes…within toString() method, format your class variables into one String object and return that String public String toString() { String a = “Sides: ” + getSides(); a += “ Length: ” + getLength(); a += “ Area: ” + getArea(); return a; } RegularPolygon square = new RegularPolygon(4, 10); System.out.println(square); // prints “Sides: 4 Length: 10 Area: 100”

o provides a quick way to look at state of your objects String I/O o Scanner class has two methods for reading textual input from keyboard o next method o returns reference to String object that has from zero to many characters typed by user at keyboard o String will end whenever it reaches white space: blank spaces, tabs, newline characters o nextLine method o returns reference to String object that contains zero to many characters entered by user o String object may contain blank spaces and tabs but will end when it reaches newline character o nextLine reads in whole lines of input rather than only one word at a time o an example: Scanner keyboard = new Scanner(System.in); String word1, word2, anotherLine; System.out.print("Enter a line: "); word1 = keyboard.next(); word2 = keyboard.next(); anotherLine = keyboard.nextLine(); //skip to the next line anotherLine = keyboard.nextLine(); //grab all of the next line System.out.println("word1 = " + word1); System.out.println("word2 = " + word2); System.out.println("anotherLine = " + anotherLine); Run Output: Enter a line: Hello World! This will be discarded. Enter another line: This line includes whitespace. word1 = Hello word2 = World! anotherLine = This line includes whitespace. o

formatting Strings is done with same style as using printf() method: import java.util.Formatter;

// need to import Formatter class

Formatter f = new Formatter(); f.format("%10s","Bob");

9/7/2009

String bob = f.toString(); // creates altered string variable System.out.println(bob.length()); // prints 10 System.out.println(bob); // prints ”Bob”

Lesson A11 notes: Inheritance Introduction o inheritance is a major component of OOP o primary tool for reusing your own and standard library classes o allows you to define a very general class and then later define more specialized classes based upon it o do this by adding new capabilities to existing class definitions or changing way existing methods work o inheritance saves work because the more specialized class inherits all the properties of the general class and you, the programmer, only need to program the new features o with the size and complexity of modern programs, reusing code is the only way to write successful programs in a reasonable amount of time. Single Inheritance o inheritance enables you to define a new class based on a class that already exists o new class inherits characteristics of existing class, but may also provide additional capabilities o this makes programming easier, because you can reuse and extend your previous work and avoid duplication of code. o class used as basis for defining new class is called superclass (or parent class or base class) o new class based on superclass is called subclass (or child class or derived class) o process by which subclass inherits characteristics from just one parent class is called single inheritance o some languages allow a derived class to inherit from more than one parent class in a process called multiple inheritance…difficult to determine which class contributes what characteristics to child class…Java avoids these issues by only providing support for single inheritance o example: person as superclass and student as subclass…"a Student is a Person", called an “is a” relationship Class Hierarchies o in a class hierarchy, each class has at most one superclass, but might have several subclasses o class at top of hierarchy has no superclass, sometimes called root of hierarchy o example: Principal is a Person, Student is a Person, Teacher is a Person, both HighSchoolStudent and CollegeStudent are types of Student. o in Java, syntax for deriving a child class from a parent class is: class subclass extends superclass{ // new characteristics of subclass go here }

o

several classes are often subclasses of same class…a subclass may in turn become parent class for a new subclass…this means that inheritance can extend over several "generations" of classes…for example, HighSchoolStudent is subclass of Student, which is subclass of Person class …HighSchoolStudent is considered to be a subclass of Person class

9/7/2009

o o

in Java, every class that does not specifically extend another class is a subclass of class Object…for example, Person class extends class Object class Object has a small number of methods that make sense for all objects, such as toString method, but class Object‟s implementations of these methods are not very useful and the implementations usually get redefined in classes lower in hierarchy.

Using Inheritance o following program uses class Person to represent people you might find at a school…Person class has basic information in it, such as name, age and gender…an additional class, Student, is created that is similar to Person, but has Id number and grade point average of student. public class Person { private String myName ; private int myAge; private String myGender;

// name of person // person's age // "M" for male, "F" for female

// constructor public Person(String name, int age, String gender) { myName = name; myAge = age; myGender = gender; } public String getName() { return myName; } public int getAge() { return myAge; } public String getGender() { return myGender; } public void setName(String name) { myName = name; } public void setAge(int age) { myAge = age; } public void setGender(String gender) { myGender = gender; } public String toString() { return myName + “, age: “ + myAge + “, gender: “ + myGender; }

9/7/2009

} //-----------------End of Person Class-----------------// public class Student extends Person { private String myIdNum; // Student Id Number private double myGPA; // grade point average // constructor public Student(String name, int age, String gender, String idNum, double gpa) { // use the super class' constructor super(name, age, gender); // initialize what's new to Student myIdNum = idNum; myGPA = gpa; } public String getIdNum() { return myIdNum; } public double getGPA() { return myGPA; } public void setIdNum(String idNum) { myIdNum = idNum; } public void setGPA(double gpa) { myGPA = gpa; } } //-----------------End of Student Class-----------------// public class HighSchool { public static void main (String args[]) { Person bob = new Person("Coach Bob", 27, "M"); Student lynne = new Student("Lynne Brooke", 16, "F", "HS95129", 3.5); System.out.println(bob); // or system.out.println(bob.toString()); System.out.println(lynne);// } } //-----------------End of HighSchool Class-----------------//

9/7/2009

o o o

o

Student class is a derived class (subclass) of Person an object of type Student contains myIdNum and myGPA, which are defined in Student it also has indirect access to the private variables myName, myAge, and myGender from Person through the methods getName(), getAge(), getGender(), setName(), setAge(), and setGender() that it inherits from Person constructor for Student class o statement super(name, age, gender) invokes Person class‟s constructor to initialize inherited data in superclass…when super is used in a constructor, it must

be first statement. next two statements initialize data members that only Student has protected access modifier o so far, we have only seen public and private access modifiers  public - class members that can be accessed outside class  private - class members that are inaccessible from outside class o there is a third access modifier that can be applied to an instance variable or method o if it is declared to be protected, then it can be used in class in which it is defined and in any subclass of that class o this declaration is less restrictive than private and more restrictive than public o A.P. Java subset allows use of protected with methods but discourages its use for instance variables…it is preferred that all instance variables are private…indirect access from subclasses should be done with public "getter" and "setter" methods o while protected members are available to provide a foundation for subclasses to build on, they are still invisible to public at large. o

o

Method Overriding o a derived class can override a method from its base class by defining a replacement method with same signature o for example, in Student subclass, toString() method contained in Person superclass does not reference new variables added to objects of type Student, so nothing new is printed out…we need a new toString() method in class Student: // overrides toString method in parent class public String toString() { return getName() + ", age: " + getAge() + ", gender: " + getGender() + ", student id: " + myIdNum + ", gpa: " + myGPA; }

o

a more efficient alternative is to use super to invoke toString() method from parent class while adding information unique to Student subclass: public String toString() { return super.toString() + ", student id: " + myIdNum + ", gpa: " + myGPA; }

o

even though base class has a toString() method, new definition of toString() in derived class will override base class‟s version…base class has its method, and derived class has its own method with same name:

9/7/2009

Person bob = new Person("Coach Bob", 27, "M"); Student lynne = new Student("Lynne Brooke", 16, "F", "HS95129", 3.5); System.out.println(bob.toString()); // “Coach Bob, age: 27, gender: M” System.out.println(lynne.toString()); // “Lynne Brooke, age: 16, gender: F, student id: HS95129, gpa: 3.5”

o

line bob.toString() calls toString() method defined in Person, and line lynne.toString() calls toString() method defined in Student

Interfaces o Person class defines attributes and behaviors of a person o an employment program might need only salary and employee ID o so, an Employable interface would define, but not implement, methods that set and get salary, assign ID number, and so on o Teacher class must agree to this protocol by implementing interface…to implement an Employable Person interface, a class must implement all of methods and attributes defined in interface o in Java, an interface consists of a set of attributes and methods, without any associated implementations…here is an example of a Java interface that defines behaviors of “employability”: public interface Employable Principal { public double getSalary(); public String getEmployeeID();

Teacher

Student

public void setSalary(double salary); public void setEmployeeID(String id); }

o o o

a class implements an interface by defining all the attributes and methods defined in interface implements is a reserved word for example: public class Teacher implements Employable { ... public double getSalary() { return mySalary; } public int getEmployeeID() { return myEmployeeID; } public void setSalary(double salary) { mySalary = salary; } public void setEmployeeID(String id) { myEmployeeID = id; } }

o

a class can implement any number of interfaces…a class can both extend another class and implement one or more interfaces…so, we can have things like (assuming we have an interface named Californian): public class Teacher extends Person implements Employable, Californian{ ... }

o

interfaces are useful for the following: o declaring a common set of methods that one or more classes are required to implement

9/7/2009

o

o

providing access to an object's programming interface without revealing details of its class. o providing a relationship between dissimilar classes without imposing an unnatural class relationship you are not likely to need to write your own interfaces until you get to the point of writing fairly complex programs…however, there are a few interfaces that are used in important ways in Java's standard packages…you'll learn about some of these standard interfaces in future lessons

Lesson A12 notes: Iterations Introduction o solving problems on a computer often requires repetition of a block of code: reading in data from a file, outputting to a file, adding numbers, etc o Java provides three ways for repeating code: for loop, while loop, do-while loop while Loop o general form of a while statement is: while (expression) { statement; }

o o o o o

boolean expression must be enclosed in parentheses () statement executed by while loop can be simple statement, or compound statement with braces {}. if the expression is true, statement is executed after execution of statement, program control returns to top of while construct statement will continue to be executed until expression evaluates to false

o

following loop will print out integers from 1-10. int number = 1; while (number = 0

total

count

smallest

undefined 65 23 81 17 45 -1

undefined

0 65 88 169 186 231

0 1 2 3 4 5

INT_MAX 65 23 23 17 17

true true true true true false

o when loop is terminated, key variables (total, score, and smallest) contain correct answers. for Loop o for loop has same effect as while loop, but uses different format…general form is: for (statement1; expression2; statement3) { statement4; }

o

for loop is typically set up as follows. statement1 initializes loop variable expression2 is boolean expression statement3 alters key value, usually via increment/decrement statement statement4 is task to be done during each iteration

9/7/2009

o

example used to print integers 1-10 for (int loop = 1; loop 0) { steps += 4;//count 2 gets and 2 sets Comparable temp = list.get(inner); list.set(inner,list.get(inner + 1)); list.set(inner + 1,temp); } } } }

o o o o

as size of data set doubles, number of steps executed increases by approximately four times Bubble Sort is an example of a quadratic algorithm in which number of steps required increases at a quadratic rate as size of the data set increases. a quadratic equation in algebra is one with a squared term, like x2 in sorting example, as size of array increases to N, number of steps required for any of quadratic sorts increases as a function of N2

Animated Sort Simulations o web site http://www.cs.hope.edu/~alganim/ccaa/sorting.html, provides animated sorting simulations Sorting Objects o sorts above compare Integers…comparison is built into Integer class o what if we wanted to write a sort that could work on Strings?...cannot use „ 0) { //swap list[inner] & list[inner+1] String temp = list.get(inner); list.set(inner, list.get(inner + 1)); list.set(inner + 1, temp); } } } }

o

if able to sort data, must be an order defined for it…classes that have an order should have a compareTo method…Java defines an Interface, Comparable, just for this purpose

9/7/2009

o

to make a BubbleSort that will work on any objects that implement Comparable, make following changes, again underlined void bubbleSort(ArrayList list) { for (int outer = 0; outer < list.length - 1; outer++) { for (int inner = 0; inner < list.size()-outer-1; inner++) { if (list.get(inner).compareTo(list.get(inner + 1) > 0) { //swap list[inner] & list[inner+1] Comparable temp = list.get(inner); list.set(inner, list.get(inner + 1)); list.set(inner + 1, temp); } } }

o o

this method is reusable because we can use it to sort any Comparable object compareTo interface follows interface java.lang.Comparable int compareTo(Object // returns value < 0 // returns value = 0 // returns value > 0

o

other) if this is less than other if this is equal to other if this is greater than other

remember to consider whether it makes sense to compare objects that you build…if it does, implement Comparable Interface…also provide an equals method for your class

Lesson A18 notes: Merge and MergeSort Introduction o in Lesson A17, Quadratic Sorting Algorithms, we saw how number of steps required increased N2 when sorting N elements o in this lesson, we will study a recursive sort, called mergeSort that works by dividing lists in half o recursive mergeSort produces a dramatic increase in efficiency in comparison with the N2 order of quadratic sorts o concept of dividing problem in two is used in several other classic algorithms o recursion makes it easier to define problem and code solution Non-Recursive MergeSort o overall logic of mergeSort is to "divide and conquer" o divide list into two (or more) approximately equal-sized parts, sort each with selection sort, then merge the two using an algorithm to be discussed below o here is a non-recursive mergeSort method

9/7/2009

// list A is unsorted, with A.size() values…first is index of first value // last is index of last value… first < last void mergeSort (ArrayList A, int first, int last) { int mid; mid = (first + last) / 2; selectionSort (A, first, mid); selectionSort (A, mid+1, last); merge (A, first, mid, last); }

o o

a modified selection sort will have to be written to sort a range of values in list A…likewise, merge method will have to be modified to internally merge two halves of the array into one ordered array example to illustrate non-recursive mergeSort U ns o rte d Lis t 34 23 48 35 37

3 1 1 1 7 ... r e s t o f l i s t ...

Lis t A fte r S o rting E a c h H a lf 23 34 35 48

o

because two sublists are stored within one array, easiest approach is to merge two sublists into another array, then copy temp array back to original

Lis t A

Temp

o

o

3 1 1 1 7 3 7 ... r e s t o f l i s t ...

23 34 35 48

3 1 1 1 7 3 7 ... r e s t o f l i s t ...

3 1 1 1 7 2 3 3 4 3 5 3 7 4 8 ... r e s t o f l i s t ...

then copy Temp back into List A: Lis t A

3 1 1 1 7 2 3 3 4 3 5 3 7 4 8 ... r e s t o f l i s t ...

Temp

3 1 1 1 7 2 3 3 4 3 5 3 7 4 8 ... r e s t o f l i s t ...

this version of merge will need to work with sections of ArrayList A…here is a proposed parameter list for merge: /* merge two sorted sublists within A into one continuous sublist from A[first] .. A[last]. The left list ranges from A[first]..A[mid]. The right list ranges from A[mid+1]..A[last]. */

9/7/2009

void merge (ArrayList A, int first, int mid, int last)

A Merge Algorithm o recursive version of mergeSort will require above version of merge, but first a simpler merge algorithm o method header and specifications of merge method are given below…assume ArrayList definitions from sorting template program in Lesson 17 apply /* Preconditions: Lists A and B are non-empty and in sorted nondecreasing order Action: Lists A and B are merged into one ArrayList, C Postcondition: List C contains values from A and B, in nondecreasing order */ void merge (ArrayList A, ArrayList B, ArrayList C)

o

o

merge method breaks down into four cases: a. ArrayList A is done, so pull value from ArrayList B b. ArrayList B is done, so pull value from ArrayList A c. Neither is done, and if A[i] < B[j] (where i & j are index markers in lists A and B) then pull from ArrayList A d. Neither is done, and if B[j] 3, remainder 259 259/( 162) -> 1, remainder 3 3/( 161) -> 0, remainder 3

o

so 12547 in decimal number system is equivalent to 310316 in hexadecimal system

Binary o binary works same way as octal and hexadecimal o binary is base 2, so only digits used are 0 and 1 and place values are all powers of 2 23 8 o o

22 4

21 2

20 1

2-1 1/2

2-2 1/4

a binary digit is called a bit examples converting from decimal to binary 13 -> 1101 (1*23 + 1*22 + 0*21 +1*20) convert 482 to binary find largest power of two that divides into 482: 28 or 256 482/256 = 1, subtract to get the leftover, 226. check to see if 27, 128 goes into 226…only have the choice of 1 or 0 so this will be simple to calculate: 226 – 128 -> 98 (another 1) 98-64 -> 34 (another 1) 34-32 ->2 (another 1) can‟t subtract 16 (so a 0 goes here) can‟t subtract 8 (another 0) can‟t subtract 4 (another 0) 2 – 2 -> 0 (another 1) can‟t subtract 1 (another 0) Answer: 1111000102

Short Cuts Between Binary, Octal, and Hexadecimal

o there is a relationship between binary, octal, and hexadecimal numbers o binary is base 2, octal is base 8(23) and hexadecimal is base 16(24) o convert binary number 101101011010111 to hexadecimal o starting at rightmost digit, split number into groups of 4: 101 1010 1101 0111 o each of these groups has 4 binary digits that can range from 0 –15…this is exactly value of one hexadecimal digit, so match each group of four bits with one hexadecimal digit: 9/7/2009

Binary Number Groups 101 1010 1101 0111

Hexadecimal Equivalent 5 A D 7

o so our binary number is equivalent to 5AD716 o going from hexadecimal reverses procedure so each hexadecimal digit expands to 4 bits o same process occurs between octal and binary using only 3 bits How this Relates to Computers and Overflow Errors o modern computers are binary computers…they are made up of switches…each switch is either on or off at any one time…everything we put into the computer (numbers and letters) must be converted to binary numbers o overflow error o if we had only 8 bits for our integers and there were no negative numbers 27 128

26 64

25 32

24 16

23 8

22 4

21 2

20 1

o

then the numbers available to us would range from 0000 0000 to 1111 1111 (binary), which is 0 to 255 (decimal) o attempting to put a larger number into an integer would result in an overflow error o see charts in Lesson A3 for minimum and maximum values for the different types of primitive data types o

round-off error o arises when using numbers that have decimal places o assume allocate in our 8-bit storage 6 bits for the mantissa (the part to the left of the decimal place) and 2 bits for the fractional portion…this storage will hold numbers from 0 to 63.75. 25 32 o

24 16

22 4

21 2

20 1

2-1 1/2

2-2 1/4

let‟s convert 7.25 to our binary representation 25 0

o

23 8

24 0

23 0

22 1

21 1

20 1

2-1 0

2-2 1

now try 7.4…first 6 bits are same, 000111, but only four choices for decimal places: 00 01 10 11

-> -> -> ->

0 .25 .5 .75

9/7/2009

o o o o o

so we would have to choose between .25 and .5 this is called round-off error converting from decimal numbers with fractional parts to a binary representation can cause errors…we are using a very simplified version here, so errors would usually occur much further out in the decimal places most of time we would not see these errors but as programmers, we should be aware of them this is why it is never a good idea to compare two floating numbers using “==”…it is much safer to compare the two and check for a certain level of accuracy (Math.abs(x – y)< .000000001)

o

is better than (x == y)

o this is also why a programmer should choose best data type for the job under-flow error o let's use our 8-bit storage scheme again, and try to store decimal number 0.1 25 0 o

24 0

23 0

22 1

21 1

20 1

2-1 0

2-2 1

first 6-bits are 000000. Remember the four choices of decimals: 00 01 10 11

-> -> -> ->

0 .25 .5 .75

o the number we are trying to store is too small for our storage scheme o converting from decimal numbers to binary may not work for numbers very close to 0

Lesson A22 notes: General Computer Knowledge Introduction o computers are very complex and interesting machines o any computer programmer should know as much about them as possible

Hardware o o o o

a computer must have a location to store information that is being manipulated when computer is engaged in processing data, it is stored in computer‟s primary memory, generally Random Access Memory (RAM)…primary memory only holds data for as long as computer is powered up…it is lost when computer is shut down secondary memory is generally slower. higher capacity, and does not need a constant current, so it is useful for long-term storage…hard disk drives, floppy disk drives, and flash drives, as well as to optical discs such as CD-ROMs and DVDs Central Processing Unit (CPU) conducts all the calculations…housed in a silicon chip called a microprocessor…understand basic computer instructions provided by computer's software…even though CPUs are often physically small, they can contain millions of parts

9/7/2009

o

hardware means computer components that can actually be physically touched, including storage devices (such as disk drives), display devices (such as computer monitors or screens), output devices (printers, speakers), input devices (keyboards, mice, joysticks, scanners) and other peripherals (modems and network cards)

Software o software is a general term for all the computer instructions and data (programs or applications) that exist on a computer…stored in memory…do not have a tangible aspect o range from computer games to word processors (applications software) to the computer‟s operating system (OS or system software), which manages and controls all the other software on the system o operating systems have been evolving for many years and have become more and more advanced…major operating systems competing for the personal computer market today are: o Microsoft Windows (i.e., 2000, NT, XP Home, XP Pro) o Apple Macintosh (i.e., OS 8, 9, X, Tiger) o Linux (there are dozens of operating systems based on Linux) o main object of this curriculum is to teach students how to create their own computer software o when creating computer software programs, a language translator and compiler are required to convert the Java code into software 'language' that CPU is able to understand…without these tools, it would be necessary to program computers entirely in binary, with 1‟s and 0‟s Networking o network of computers is defined as two or more computer systems connected to each other, in order to communicate and share data o simple linking of computers found close together or span a relatively large geographical area o wide-area network (WAN) consists of two or more local-area networks (LANs) o largest WAN is the Internet, an interconnected system of networks which has been expanding rapidly around the world over the last couple of decades…millions of websites today o another feature of networking is called thin client – exists computer (client) has little or no hardware or software on it…depends on a host server for data and processing Ethics o power and expansion of computers and networking has brought many problems and ethical issues o anti-virus, anti-spyware, anti-spam, and privacy protection software programs o computers getting infected with a malicious computer virus and behaving strangely o spyware sends data to third parties o new field of criminal justice that deals with computer crimes, such as theft of usernames and passwords, identity theft, denial of service attacks, alteration of websites, illegal or offensive material posted on websites or received in emails, predatory sexual behavior, copyright infringement, unregulated gambling, and more o sexual predators hide behind a screen name o computer hackers attempt to get bank account and credit card information o pornography and gambling can be hard to regulate over Internet o copyright infringement much more likely to go unnoticed o important to think about ramifications of one's own actions when using computer technology

9/7/2009

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF