Week 6: Review Java Language Elements: special characters, reserved keywords, variables, operators & expressions, syntax, objects, scoping, Robot world 7 will be used on the midterm. Java is Case Sensitive Special Characters // in line comment. /* */ block comment. ; end of line, in for loop syntax. { code block. dot : used to list a member of an object., comma : separates parameters or arguments in a list, values in an array. ( ) encloses parameter lists, used in syntax of conditionals and loops. used to enclose String literals. used to enclose char literals. [] used in array definitions. APSC142 - Prof.McLeod 1
Reserved Keywords (Can t be used as variable names) Used in APSC142, so far: boolean, byte, char, class, do, double, else, final, float, for, if, int, long, new, private, public, return, short, static, void, while You should know what these mean and where they are used! Other keywords: abstract, break, case, catch, continue, default, extends, finally, implements, import, instanceof, interface, native, null, package, protected, super, switch, synchronized, this, throw, throws, try (Underlined keywords will be discussed later in course) APSC142 - Prof.McLeod 2
Variables - Primitive Types Integral Types: byte, short, int, long, char For byte, from -128 to 127, inclusive For short, from -32768 to 32767, inclusive Forint, from -2147483648 to 2147483647, inclusive For long, from -9223372036854775808 to 9223372036854775807, inclusive For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535. A variable of the char type represents a Unicode character. Can also be represented as a or 8, etc. Floating Point Types: float, double For float, (4 bytes) roughly ±1.4 x 10-45 to ±3.4 x 10 38 to 8 significant digits. For double, (8 bytes) roughly ±4.9 x 10-324 to ±1.7 x 10 308 to 17 significant digits. APSC142 - Prof.McLeod 3
Variables - Types (Cont.) Boolean Types: boolean is either true or false. String is an object, not a primitive type. class is an object. (Arrays are objects.) APSC142 - Prof.McLeod 4
Variable Declaration & Naming Rules Variables must be declared before they are used. Variable names cannot start with a number, but otherwise can use a..z, A..Z, 0..9 and _. No spaces in variable names. Convention is that variables start with a lower case letter. Constants are all in upper case. Method names start with a lower case letter. Class names start with an upper case letter. Use descriptive variable names! Variables are usually nouns. Declaration examples: int numstudents; boolean studentisasleep; int numeggsindozen = 12; int icounter, jcounter, kcounter; double bigarea = 1.2e23; APSC142 - Prof.McLeod 5
Variable Declaration - Constants & Scoping The keyword final is used to declare constants: final int NUMSCREENROWS = 25; Hint: usually initialize after declaration. Variables declared within a method are local in scope to that method. You don t use private or public or static. Variables declared at the same level as methods within a class are called attributes must be declared public or private and can be static. Examples: public static int numstudents = 50; private final double R = 0.08206; public means the attribute can be changed. private attributes cannot be viewed or changed. static attributes occupy the same memory location for each child object. APSC142 - Prof.McLeod 6
Expressions - Operators Listed in order of operator precedence: () (parentheses). ( dot operator) ++ (increment) -- (decrement) + (unary plus) - (unary minus)! (boolean not ) (type) (type cast) * (multiplication) / (division) % (modulus) + (addition or concatenation) - (subtraction) < (boolean less than ) <= ( less than or equal to ) > ( greater than ) APSC142 - Prof.McLeod 7
Expressions - Operators (Cont.) >= ( greater than or equal to ) == ( equal to, don t use with String s!)!= ( not equal to ) && (boolean and ) (boolean or ) = (assign) += (add and assign) -= (subtract and assign) *= (multiply and assign) /= (divide and assign) %= (modulo and assign) Example: amount *= 25; is the same as: amount = amount * 25; You should know what all these operators do, and in what order they are processed. APSC142 - Prof.McLeod 8
Expressions - (Cont.) Expressions can contain operators, variables and literal values. Literals are things like north, 2, 1e-4, true, etc. Watch out for integer division!: 2.0 / 5.0 evaluates to 0.4. 2/5 is 0. Type casting: Any integer type can be implicitly changed into a float or double type. You must cast types to go in the other direction. For example: (int)4.8 evaluates to 4. The double value 4.8 has been cast to an int type. Note that casting truncates, not rounds. APSC142 - Prof.McLeod 9
Conditionals - if Statements Simple if statement syntax: if ( boolean_expression ) statement_when_true; else statement_when_false; With statement blocks: if ( boolean_expression ) { block_of_code_when_true else { block_of_code_when_false Note that else part is optional. APSC142 - Prof.McLeod 10
Conditionals - if Statements (Cont.) Branching if statement: if ( boolean_expression ) { block_of_code_when_true else if ( boolean_expression2 ) { block_of_code_when_2_true else if ( boolean_expression3 ) { block_of_code_when_3_true else if ( boolean_expression4 ) { block_of_code_when_4_true. else { block_of_code_when_all_are_false if statement is ended when one condition is true, no other branches are tested. Note that else part is optional. APSC142 - Prof.McLeod 11
Conditionals -switch Statement switch ( controlling_expression ) { (etc.) case case_label1: statement; statement; break; case case_label2: statement; statement; break; case case_label3: statement; statement; break; default: statement; statement; break; Note: case_label s are constants of same type as controlling_expression. APSC142 - Prof.McLeod 12
Loops Loops execute a block of instructions until a given condition becomes false. Three kinds of loops: while, do while, for. while loop syntax: while ( boolean_expression ) { block_of_code Loop executes until boolean_expression evaluates to false. Note, if boolean_expression is false to start with, loop will not execute at all. do while loop syntax: do { block_of_code while ( boolean_expression ); This loop will execute at least once. APSC142 - Prof.McLeod 13
Loops Cont. for loop syntax: for ( initialization; boolean_expression; update) { block_of_code Example: int sumnumbers = 0; for (int i=1; i <= 20; i++) { sumnumbers = sumnumbers + i; System.out.println(sumNumbers); Hint: Avoid using declarations inside loops. Watch out for infinite loops!! APSC142 - Prof.McLeod 14
String literals: String Class Press <enter> to continue. String variable declaration: String teststuff; or: String teststuff = A testing string. ; String concatenation ( addition ): String teststuff = Hello ; System.out.println(testStuff + to me! ); Would print the following to the DOS window: Hello to me! Note that including another type in a String concatenation calls an implicit tostring method. So, in: System.out.println( I am + 2); the number 2 is converted to a String before being concatenated. The digits given after a decimal point in a float or double type variable can be impressive! APSC142 - Prof.McLeod 15
String Class, Cont. A String variable is an object, so it has methods as well as a value. String methods include: length() equals(otherstring) equalsignorecase(otherstring) tolowercase() touppercase() trim() charat(position) substring(start) substring(start, End) indexof(searchstring) APSC142 - Prof.McLeod 16
Examples: String Class, Cont. int i; boolean abool; char achar; String teststuff = A testing string. ; i = teststuff.length(); // i is 17 abool = teststuff.equals( a testing string. ); // abool is false abool = teststuff.equalsignorecase( A TESTING STRING. ); // abool is true achar = teststuff.charat(2); // achar is t i = teststuff.indexof( test ); // i is 2 APSC142 - Prof.McLeod 17
Escape Characters: String Class, Cont. \ Double quote \ Single quote \\ Backslash \n Go to beginning of next line \r Go to beginning of current line \t Tab character For example: String teststuff = Line1\nLine2 ; System.out.println(testStuff); Would print the following to the DOS window: Line1 Line2 APSC142 - Prof.McLeod 18
Defining Methods Classes are containers for attributes and methods called encapsulation. Attributes and methods are members of a class. Attributes or instance variables hold data, methods do things. When a child object is created, it inherits all the attributes and methods of the parent object. For example: Robot BagOBolts = new Robot(); BagOBolts, the child object, inherits all the attributes and methods defined in the parent Robot class (ie. Defined in the Robot.java file). APSC142 - Prof.McLeod 19
Defining Methods Cont. Example (in first Robot.java file): public class Robot { //***********attributes********** public int row; public int column; public String direction; //************methods************ public void move() { // lines of code here public void turn() { // lines of code here public void printlocation() { // lines of code here // end of class Robot APSC142 - Prof.McLeod 20
Defining Methods Cont. Syntax: Scope Optional_static Return_type Method_name(Parameter_list) { Lines_of_code Scope is either public or private. public means that the method is available to other objects. The use of private allows for information hiding. Optional_static is the optional keyword static (Talk about later ) Return_type is either void, or a type such as int or double, etc. or a defined object such as String. void is used when the method does not return anything. If void is not used, then there must be at least one return statement in the method. APSC142 - Prof.McLeod 21
Defining Methods Cont. Method_name is whatever you want follow variable naming restrictions. Be descriptive (a verb). Parameter_list provides a means of passing values, or parameters, into a method. It is optional. It can consist of one or many parameters, separated by commas. Each parameter type must be declared in the parameter list. Examples of methods: public void PrintHello() { System.out.println( Hello ); public void PrintHelloName(String yourname) { System.out.println( Hello + yourname); APSC142 - Prof.McLeod 22
More Examples: Defining Methods Cont. public void PrintAvg(int a, int b) { System.out.println((a + b) / 2); public double Average(double a, double b) { return (a + b) / 2; public int Lowest(int a, int b) { if (a <= b) return a; else return b; Note that return can be used in a void method to end the method at the return statement rather than at the end of the code. APSC142 - Prof.McLeod 23
Defining Methods Cont. Scoping of variables and methods the use of public and private. Can declare variables inside a method: public double Average(double a, double b) { double holdaverage = (a + b) /2; return holdaverage; holdaverage is a local variable to the method. It is not defined or accessible outside the method. Instance variables (or attributes) declared in a class, at the same level as the methods, can be used by any method in the class. If an instance variable is declared public it is also available to objects outside the class as a member of the class. If the variable is declared private it can only be used within the class. If an method is declared public it is also available to objects outside the class as a member of the class. If the method is declared private it can only be used within the class. APSC142 - Prof.McLeod 24
Defining Methods Cont. If the static keyword is used in a method definition inside a class, it allows that method to be used without first having to instantiate the class. For example: String Junk = SavitchIn.readLine(); readline() is a public static method defined in the SavitchIn class. APSC142 - Prof.McLeod 25
Method Overloading A method can have the same name in many different classes. Overloading is when a method name is used more than once in the same class. The rule is that no two methods with the same name within a class, can have the same number and/or types of parameters in the method declarations. The method signatures must be different. Why bother? Allows the user to call a method without requiring him to supply values for all the parameters. Allows the programmer to keep an old method definition in the class for backwards compatibility. How does it work? Java looks through all methods until the parameters match with what is supplied by the user. If none match, Java tries to convert types in order to get a match. APSC142 - Prof.McLeod 26
Method Overloading Cont. Overloaded (and simplified) move() method in Robot class: // Move the robot a single space in the direction // it is facing. public void move() { if (direction.equalsignorecase("north")) row = row - 1; else if (direction.equalsignorecase("south")) row = row + 1; else if (direction.equalsignorecase("east")) column = column + 1; else if (direction.equalsignorecase("west")) column = column - 1; // end move() method // Moves the robot numofspaces in same direction public void move(int numofspaces) { for (int i=1; i <= numofspaces; i++) move(); // end move(numofspaces) method APSC142 - Prof.McLeod 27
Constructors In older robot versions, for example: Robot ChugAlong = new Robot(); ChugAlong.row = 0; ChugAlong.column = 1; ChugAlong.direction = south ; ChugAlong.numFlares = 20; When using Robot Version 7, you *must* use: Robot ChugAlong = new Robot(0, 1, south, 20); Robot World 7 attributes, constants and arrays are not longer public, they are private - they way they should have been all along! You can no longer use myrobot.row to get at the robot s row. You will need to use the appropriate get method. APSC142 - Prof.McLeod 28
Constructors Cont. Can and should overload constructors. Note that constructor definition cannot contain a return type and does not even have void. A Constructor without parameters is called the default constructor. For example, the Robot() default constructor works to put the robot at the first square from the north-west corner that does not have a wall, faces him east and gives him zero flares. Constructors are called with the new keyword when an object is created. Once an object is created ( instantiated ) then the constructor cannot be called again for that object. So, the only way to change the robot s direction or position is to use the move(), turn(), teleport(), etc. methods. Robot World 7 does not have any set methods for the attributes. APSC142 - Prof.McLeod 29
Constructors Cont. What other reasons are there to use constructors? Suppose we tried to use: Robot BadBoy = new Robot(0, 12, South ); Constructors can check for and compensate for illegal values. For example: // A three-parameter Robot constructor public Robot (int initrow, int initcol, String initdir) { if (initrow < 0) row = 0; else if (initrow > MAX_ROW) row = MAX_ROW; else row = initrow; if (initcol < 0) column = 0; else if (initcol > MAX_COL) column = MAX_COL; else column = initcol; direction = initdir.trim(initdir.tolowercase()); Constructors can also make assumptions and create values for those attributes the user does not supply. APSC142 - Prof.McLeod 30
Mutators and Accessors If class attributes are public, then they can still be directly changed even after the constructor has been run. In order to prevent direct changes to the attributes, make them private. The constructors can still set the attribute values when the object is created, but what if we want to see or set the attribute values later in the program? Mutator or set methods can change attribute values. Accessor, Selector or get methods can provide attribute values. Robot 7 has various get methods, such as getrow(), getcol() and getnumholding(). Robot 7 does not have any set methods. APSC142 - Prof.McLeod 31
Static Methods A public static method can be called without having to create ( instantiate ) an object. For example, all SavitchIn methods are static: String Junk = SavitchIn.readLine(); works. Instead of: SavitchIn readmethods = new SavitchIn(); String Junk = readmethods.readline(); (This also works ) Static methods cannot refer to non-static attributes or non-static methods, without creating an object first. Robot 7 has static get methods: getmaxrow(), getmaxcol(), and numrobots(). So they can be called as in Robot.getMaxRow(). APSC142 - Prof.McLeod 32
Static Variables One aspect is similar to static methods. A public static variable is available without having to create an object. For example, the Math class provides a value for π: double circlearea = Math.PI * radius *radius; Somewhere in the Math class is: public static final double PI = 3.141592653589793; Every object created from the class can refer to the same static variable (also called class variable ). Static variables are called static because they occupy a static area in memory. Normally each object has its own, completely independent copy of the class s attributes in separate memory locations. Robot 7 has a number of private static constants and variables. APSC142 - Prof.McLeod 33