Fina Final R l Rev eview!!! w!!! Classes and Objects Program - - PowerPoint PPT Presentation

fina final r l rev eview w
SMART_READER_LITE
LIVE PREVIEW

Fina Final R l Rev eview!!! w!!! Classes and Objects Program - - PowerPoint PPT Presentation

Fina Final R l Rev eview!!! w!!! Classes and Objects Program Statements (Arithmetic Operations) Program Flow String In-depth java.io (Input/Output) java.util (Utilities) Exceptions Cla lass sses Bas es


slide-1
SLIDE 1

Fina Final R l Rev eview!!! w!!!

  • Classes and Objects
  • Program Statements (Arithmetic Operations)
  • Program Flow
  • String In-depth
  • java.io

(Input/Output)

  • java.util

(Utilities)

  • Exceptions
slide-2
SLIDE 2

Cla lass sses – Bas es – Basic ic Ove Overv rview Cla lass sses – Bas es – Basic ic Ove Overv rview

A class is a container for data values (attributes) and actions (methods). It can contain only actions (generally done with static methods only). It can also contain both in which case it usually describes an object either tangible or abstract. This blueprint of an object needs to have a special method that gives initial values to the attributes (constructor). Examples of only action classes:

  • Integer

(contains action to convert String to int)

  • Math

(contains a bunch of math functions: sqrt, cos, arctan, ...) Examples of Blueprint classes:

  • Employee(Attributes: name, position, salary, Actions: getPay)
  • Board

(Attributes: board, Actions: userMove, full)

slide-3
SLIDE 3

Cla lass sses – Bas es – Basic ic Ove Overv rview Cla lass sses – Bas es – Basic ic Ove Overv rview

//import statements here import java.io.*; ... public class <className> { //attributes private <type> <name>; private int x; ... //constructors public <className> (<params>) { } public <className> (int x1) { x = x1; } ... //methods public <returnType> <methodName> (<params>) { //code to do action //return if returnType is not void } public int getX () { return x; } ... }

slide-4
SLIDE 4

Cla lass sses – At es – Attr tribut butes Cla lass sses – At es – Attr tribut butes

An Attribute is a variable that is stored within the class that describes a value that the object the class describes has. These are primarily defined a private since, we do not want anyone explicitly changing the value. They are defined outside any method body, but are within the class, as such any method within the class has access to it as well. This in contrast to local variables that are defined within methods...only the method which the variable is defined in has access.

public class Attr { private int x; public Attr () { x = 0; } public void localDemo() { int y = 5; System.out.println(“X is “+x); //Ok since x is an attribute System.out.println(“Y is “+y); //Ok since y is local variable in the current method } public void globalDemo() { System.out.println(“X is “+x); //Ok since x is an attribute System.out.println(“Y is “+y); //ERROR! Y only exists within the localDemo method } }

slide-5
SLIDE 5

Cla lass sses – At es – Attr tribut butes Cla lass sses – At es – Attr tribut butes

Since attributes are variables, but defined in the class scope, they follow the same rules as local variables. They must be defined once and only

  • nce, this is done inside the class (refer to slide 3). They must be declared

with the keyword private then the data type, common data types are below, they can take on any reference type (i.e. class name, see slides from week 9 (Point attribute in the Circle class)): Common Data Types:

  • int
  • double
  • char
  • boolean
  • String
slide-6
SLIDE 6

Cla lass sses – At es – Attr tribut butes Cla lass sses – At es – Attr tribut butes

Attributes can take on array types as well. Arrays are accessed using indexes ranging from [0, size-1] Generic description of Arrays below: Array Declaration:

<type> [] <name>; //sets up memory for an array (no size yet)

Array Assignment:

<name> = new <type> [<size>]; //sets the size of the array

Array Initialization

<type> [] <name> = new <type> [<size>]; //creates an array of specified size //and type

Array Access:

<name>[<index>] //gets the value store in the array at index

slide-7
SLIDE 7

Cl Classes – C – Const structo tors rs Cl Classes – C – Const structo tors rs

A Constructor's job is to set-up an object initially, they should assign starting values to the attributes (e.g. In Point it set the x, y coordinates to 0, 0). Constructors can take parameters just like methods, and use them for the initialization process. Constructors are always defined as public, and have no return type. They also have the EXACT same name as the class, case and all. Then they have parenthesis for any parameters. e.g. If you have a class called Point you could have the two constructors:

public Point() { x = 0; y = 0; } public Point(int px, int py) { x = px; y = py; }

slide-8
SLIDE 8

Cla lass sses es – Met Methods Cla lass sses es – Met Methods

Methods usually begin with the public keyword and are followed by the return type...this is the kind of information (int, double, String, ...) that the method passes back to the code that is making the method call (invoking code). These methods behave like queries, (e.g. gameOver, getPay, ...) Methods that do not return data, behave like commands, doing a specific action (e.g. userMove, displayBoard, ...), these methods specify their return type as void. Methods can have parameters, which are values that are passed from the invoking code to the method. Example:

// takes an integer for the number of hours worked from the invoking code // returns the total pay for the week public double getPay (int hours){ return salary * hours; //assume salary is an attribute }

slide-9
SLIDE 9

Progr

  • gram S

m Sta tatement tements Progr

  • gram S

m Sta tatement tements

Program Statements are commands that perform a specific action, or determine program flow and are what are executed by the program. These appear only within methods. Java begins with the statements found in the main method: public static void main(String [] args) { Statements that perform a specific action always end in semi-colons. Common examples are ones that modify the value of variables, or print to the screen. Statements that control the flow of the program, usually end in braces, as these enclose code for possible paths (e.g. if a condition is true perform the statements within a set of braces)

slide-10
SLIDE 10

St Statement tements – Metho s – Method Ca d Calli ling ng St Statement tements – Metho s – Method Ca d Calli ling ng

You can call methods, jump to the method's body and execute the statements that are there to perform a series of steps in one line. This is why we have methods: Calling static methods (parseInt is static)

<className>.<methodName>( <arguments> ); //executes methodName which is from className, and is passed //values specified as arguments

Calling non-static methods (need an object created)

<className> <objName> = new <className> ( <constructorArgs> ); //creates an object of type className <objName>.<methodName>( <arguments> ); //executes methodName which is from className

slide-11
SLIDE 11

Sta Statements ents - Print

  • Printing

ing Sta Statements ents - Print

  • Printing

ing

Two statements exist for printing:

System.out.print( <What is to be printed> ); //this prints out the text specified and sets the cursor on //the same line so that whatever is printed next appears on //the same line System.out.print( <What is to be printed> ); //this prints out the specified text, and sets the cursor //to the next line so that the next set of text to be //printed appears on the following line.

slide-12
SLIDE 12

Sta tatement tements - Ar s - Arithmeti thmetic Sta tatement tements - Ar s - Arithmeti thmetic

Numeric Variables (int, double) can be modified using built-in

  • perations:

+ addition

  • subtraction

* multiplication / division % modulus = Assignment, stores what is on the right side into the left e.g. x = 5 stores the value 5 into the variable x.

slide-13
SLIDE 13

Program Fl m Flow

  • w – if

– if, els else Program Fl m Flow

  • w – if

– if, els else

The if statement uses conditionals to determine what code to run. When the condition evaluates to true then the code following the if-statement is run, using braces specifies a set of statements to run. Using an else in conjunction will result in the code following the else to be run when the condition evaluates to false. The code continues as normal after if- statement is finished if ( <condition> ) { //code to run when condition is true } else { //code to run when condition is false } Note: else part is optional

slide-14
SLIDE 14

Progr

  • gram Flo

m Flow w – Co – Cond ndit itio ions Progr

  • gram Flo

m Flow w – Co – Cond ndit itio ions

There exists some commands that can be used to compare: == checks to see if variables/values on both sides are equivalent < strictly less than <= less-than or equal > strictly greater than >= greater-than or equal != not equal || combines two conditionals with an OR statement && combines two conditionals with an AND statement

slide-15
SLIDE 15

Pro Progr gram F Flo low – Lo w – Loop

  • ps

Pro Progr gram F Flo low – Lo w – Loop

  • ps

Loops repeat a section of code repeatedly until a condition is false (in the case of while and do-while loops), or a specific number of times (for- loop). The generic form of the while & do-while are described below: while ( <condition> ) { //code to run, when condition is true, will not //stop until condition is false } do { //same as while, except, code run first then //checked. } while (<condition> );

slide-16
SLIDE 16

Pro Progr gram F Flo low – Lo w – Loop

  • ps

Pro Progr gram F Flo low – Lo w – Loop

  • ps

for loops are loops that typically use counter variables (integer variables that either keep track of the number of times the loop has run, or refers to an index of an array or String). Initialization sets the counter variable to a starting value, condition behaves the same as in all other loops, and update is where you alter the counter variables value in order to progress the loop to a terminating state. for ( <initialization>; <condition>; <update> ){ //code that is repeated while the condition is met }

slide-17
SLIDE 17

Str tring - Meth ng - Methods

  • ds

Str tring - Meth ng - Methods

  • ds

The String class is a special type that is built into java. It has several built- in methods. Since it is a class (reference type) you cannot use == to compare two Strings. equals

<stringName1>.equals( <stringName2> ); //returns either true if stringName1 matches (case and all) stringName2

substring

<stringName1>.substring( <index> ); //returns a new String that contains every letter including and past the letter //at index from the String stringName1 <stringName1>.substring( <index1>, <index2> ); //returns a new String that contains every letter including and past the letter //at index1 up to but not including the letter at index2 from the String //stringName1

charAt

<stringName1>.charAt( <index> ); //returns a char, it is the letter that appears in stringName1 at index

slide-18
SLIDE 18

Strings Strings - C

  • Conve
  • nvertin

rting Strings Strings - C

  • Conve
  • nvertin

rting

Any information that is stored as a String can be converted to numeric data using a parse method from either the Integer or Double class. int conversion

Integer.parseInt( <stringName> ); //returns an int, the integer represenation of stringName

double conversion

Double.parseDouble( <stringName> ); //returns an int, the integer represenation of stringName

slide-19
SLIDE 19

java.io .io – Us – User er I Input nput java.io .io – Us – User er I Input nput

The following section is devoted to the code that is used when using the import command: import java.io.*; User Input:

BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); //creates a BufferedReader object that is linked to the command-line //(System.in) String input = r.readLine(); //waits for user input, and reads in what the user types by storing it in //the variable named input...use String conversion to get as an integer.

slide-20
SLIDE 20

java.io .io – R – Rea eadi ding/Wr ng/Writi ting ng java.io .io – R – Rea eadi ding/Wr ng/Writi ting ng

File Reading:

BufferedReader r = new BufferedReader(new FileReader(< fileName >)); //creates a BufferedReader object that is linked to the specified file String input = r.readLine(); //reads a line from the file and stores it in the variable named //input...this will have the value null if the end of the file has been //reached

File Writing:

PrintWriter pw = new PrintWriter(new BufferedWriter( new FileWriter(< fileName >); //creates a PrintWriter object that is linked to the specified file pw.println(< text >); //writes a line to the file that is specified by text which is a String //works the same way System.out.println(..) does, only writing to the file //and not the console.

Make sure to use either pw.close() or r.close() when finished reading and writing

slide-21
SLIDE 21

java.ut .util – R il – Random ndom java.ut .util – R il – Random ndom

The following section is devoted to the code that is used when using the import command: import java.util.*; Random:

Random rand = new Random(); //creates a Random object that is able to generate random numbers int num = rand.nextInt(< number >); //generates a random number in the range of 0 to (number-1), and stores it //into the variable num

slide-22
SLIDE 22

java.u va.util – String til – StringTokeni enizer er java.u va.util – String til – StringTokeni enizer er

StringTokenizer:

StringTokenizer st = new StringTokenizer(< fullString >, < delimiter >); //creates a StringTokenizer object named st that is able to get substrings //of fullString that separated by all the characters in the delimiter //String String token = st.nextToken(); //gets the next substring from the tokenizer that has not been extracted //yet, and stores it into the variable named token. boolean isDone = st.hasMoreTokens(); //checks to see if there are any tokens in the tokenizer that have not //been examined, if there are some left then true is stored in the //variable isDone, otherwise it is false. Used with loops.

slide-23
SLIDE 23

Ex Exceptions ceptions Ex Exceptions ceptions

Exception: is an error that occurs during run-time. Unlike compiler errors which are problems with syntax, where the computer doesn't understand what the programmer wants, an exception occurs when the computer knows what it needs to do...it just can't due to specific circumstances (due to user input is a good example). Generic Format of a try-catch block: try{ //Code that might cause problems }catch (<TypeOfException> e) { //Code to handle the exception }

slide-24
SLIDE 24

Fi Fina nal Tim Time Fi Fina nal Tim Time

The final will be next week during lab period, it is designed for an hour period, but you have the full two hours if you need it. It will cover all material from throughout the entire semester, but have a larger focus on methods, and classes.