Final Review!!! Classes and Objects Program Statements (Arithmetic Operations) Program Flow String In-depth java.io (Input/Output) java.util (Utilities) Exceptions
Classes Basic Overview 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)
Classes Basic Overview //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;...
Classes Attributes 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); System.out.println( Y is +y); public void globaldemo() { System.out.println( X is +x); System.out.println( Y is +y); //Ok since x is an attribute //Ok since y is local variable in the current method //Ok since x is an attribute //ERROR! Y only exists within the localdemo method
Classes Attributes 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 once, 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
Classes Attributes 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
Classes Constructors 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;
Classes 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
Program Statements 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)
Statements Method Calling 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
Statements - Printing 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.
Statements - Arithmetic Numeric Variables (int, double) can be modified using built-in operations: + 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.
Program Flow if, 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 ifstatement is finished if ( <condition> ) { //code to run when condition is true else { //code to run when condition is false Note: else part is optional
Program Flow Conditions 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
Program Flow Loops 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 (forloop). 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> );
Program Flow Loops 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
String - Methods The String class is a special type that is built into java. It has several builtin 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
Strings - Converting 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
java.io User Input 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.
java.io Reading/Writing 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
java.util Random 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
java.util StringTokenizer 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.
Exceptions 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
Final 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.