1Lecture Set 4:More About Methods and More About Operators Methods Definitions Invocations More arithmetic operators Operator Side effects Operator Precedence Short-circuitingCMSC 131 Fall 2010 Jan Plane & Ben Bederson (adapted from Bonnie Dorr)main methodpublic static void main(String args[]){// statements here} All projects and examples have defined this method No explicit call needed Parts of the line Name = main Parameter List = String args[] Return type = void Access = public -- more on this later Modifier = static CMSC 131 Fall 2010 Jan Plane & Ben Bederson (adapted from Bonnie Dorr)Other public static methods A static method is associated with a class not an individual instance (object) Must have all of the same parts as the mainpublic static returnType name(argList){body} For example – defining a method to print a number of starspublic static void printStars(int count){for (int curr = 0; curr < count; curr=count+1){System.out.print(“*”);}} For example – defining a method to print a number of starsprintStars(3);System.out.println();printStars(77);CMSC 131 Fall 2010 Jan Plane & Ben Bederson (adapted from Bonnie Dorr)MethodStars.java2method information:parameters and arguments parameter list type name for each item in the list e.g. (MyGrid grid, char where) argument list expression for each item in the list e.g. (grid, „t‟) Matched between the arguments and the parameters based on position in the listCMSC 131 Fall 2010 Jan Plane & Ben Bederson (adapted from Bonnie Dorr)Non-main static public methods: defining, invoking and commenting Defined based on a name and a list of parameterspublic static void name(parameterlist){body} Invoked by stating its name and giving an argument for each element of the parameter listname(argumentlist); Each method must have a well defined purpose That information goes into a comment before the method definition Each parameter‟s purpose should be explained Return value‟s purpose should be explainedCMSC 131 Fall 2010 Jan Plane & Ben Bederson (adapted from Bonnie Dorr)PrimesMethods.javaExpressions Java “expressions” that yield valuese.g.xx + 1 - yx == y && z == 0foo.equals (“cat”) Expressions have values of a specific type (int, boolean, etc.) Expressions can be assigned to variables, appear inside other expressions, etc.CMSC 131 Fall 2010 Jan Plane & Ben Bederson (adapted from Bonnie Dorr)3Expressions and Side Effects Some expressions can also alter the values of variablese.g. x=1 x=1 is an expression? Yes! Value is result of evaluation right-hand side of = It also alters the value of x Such alterations are called side effectsCMSC 131 Fall 2010 Jan Plane & Ben Bederson (adapted from Bonnie Dorr)Are the Following Legal? int x, y;x = y = 1;Yes. Result assigns 1 to x and to y int x = 0, y = 1;boolean b = false;if (b = (x <= y)){ x = y;}Yes. Result assigns true to b and 1 to xCMSC 131 Fall 2010 Jan Plane & Ben Bederson (adapted from Bonnie Dorr)E1OpExpr.javaOther Expressions with Side Effects Java includes abbreviations for common forms of assignment Example: increment operations (Basically equivalent to x = x + 1++x “Pre-increment”Increments x, returns the new value of x(“increment x, then return it”)x++ “Post-increment”Increments x, returns the old value of x(“return x, then increment it”) Same or Different x == x++ x == ++x Compare x++ * y++ ++x * ++y ++x * y++ x++ * ++yCMSC 131 Fall 2010 Jan Plane & Ben Bederson (adapted from Bonnie Dorr)always truenever true4Other Assignment Operators Example: decrement operations (Basically equivalent to x = x - 1--x “Pre-decrement”Decrements x, returns the new value of xx-- “Post-decrement”Decrements x, returns the old value of x“return x, then decrement it” General modification by constant General form: <var> <op with=> <constant> Examplesx += 2 equivalent to x = x+2x -= 2 equivalent to x = x-2x *= 2 equivalent to x = x*2x /= 2 equivalent to x = x/2CMSC 131 Fall 2010 Jan Plane & Ben Bederson (adapted from Bonnie Dorr)E2PrePostCompare.javaPrecedence Explains how to evaluate expressions What is value of 1 – 2 + 3 * 4? Precedence rules answer this question Higher-precedence operators evaluated first Example from math: “Please, Excuse my Dear Aunt Sally” or PEMDASMultiple and divide (higher precedence) before you add and subtract (lower precedence) Java follows “Aunt Sally‟s Rules” … but what about other operators?CMSC 131 Fall 2010 Jan Plane & Ben Bederson (adapted from Bonnie Dorr)Java Precedence Rules parentheses: ( ) unary ops: +x -x ++x –-x x++ x-- !x multiply/divide: * / % add/subtract: + - comparisons: < > <= >= equality: == != logical and: && logical or: || assignments: = += *= /= %= (these are right to left associative)CMSC 131 Fall 2010 Jan Plane & Ben Bederson (adapted from Bonnie Dorr)Higher precedence on top5Examples x * y + -zSame as (x*y) + (-z) (x <= y && y <= z || w > z)Same as ((x <= y) && (y <= z)) || (w > z) What is value of 1 – 2 + 3 * 4?= 1 - 2 + 3 * 4= 1 - 2 + (3 * 4)= (1 - 2) + 12= -1 + 12= 11CMSC 131 Fall 2010 Jan Plane & Ben Bederson (adapted from Bonnie Dorr)Should You Rely on Precedence? No! The only ones people can remember are “Please Excuse My Dear Aunt Sally” (PEMDAS) And maybe unary and increment/decrement operators Bad:if (2 * x++ < 5 * z + 3 && -w != x / 2) Better: if ((2 * x++ < 5 * z + 3)) && (-w != x / 2)) Best:if (((2 * x++) < (5 * z + 3)) && (-w != (x / 2)))CMSC 131 Fall 2010 Jan Plane & Ben Bederson (adapted from Bonnie Dorr)Short-circuiting Example As soon as Java knows an answer – it quits evaluating the expression. What does Java print?int x = 0, y = 1;if ((y > 1) && (++x == 0)){--y;}System.out.println (x);=> 0 Why? y > 1 is false The result of && will be false, regardless of second expression Java therefore does not evaluate second expression of && This treatment of &&, || is called short-circuiting Subexpressions evaluated from left to right Evaluation stops when value of over-all expression is determinedCMSC 131 Fall 2010 Jan Plane & Ben Bederson (adapted from Bonnie Dorr)6Examples What does Java print?int x = 0, y = 1;if ((y >= 1) && (++x == 0))
View Full Document