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
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
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:
(contains action to convert String to int)
(contains a bunch of math functions: sqrt, cos, arctan, ...) Examples of Blueprint classes:
(Attributes: board, Actions: userMove, full)
//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; } ... }
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 } }
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
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:
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
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; }
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 }
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)
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
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.
Numeric Variables (int, double) can be modified using built-in
+ addition
* 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.
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
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
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> );
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 }
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
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
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.
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
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
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.
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 }