290 likes | 297 Views
CSE 501N Fall ‘09 03: Class Members. 03 September 2009 Nick Leidenfrost. Lecture Outline. Boolean Expressions Methods Naming Parameter Lists Return Types Invoking / Calling Control Flow Lab 1 Overview. Boolean Expressions.
E N D
CSE 501NFall ‘0903: Class Members 03 September 2009 Nick Leidenfrost
Lecture Outline • Boolean Expressions • Methods • Naming • Parameter Lists • Return Types • Invoking / Calling • Control Flow • Lab 1 Overview
Boolean Expressions • An expression is a combination of one or more operators and operands • Last lecture we learned about arithmetic expressions – expressions dealing with numeric types as operands and the operators +, -, *, / and % • Boolean expressions compute logical results and make use of the boolean operators: Name: Java Operator AND && OR | | NOT ! XOR ^
Boolean Expressions boolean one, two; • AND (&&) – Binary operator that evaluates to true if both operands are true • OR ( | | ) – Binary operator that evaluates to true if either of the operands are true • XOR ( ^ ) – Binary operator that evaluates to true if one and only one of the operands are true • NOT ( ! ) – Unary operator that negates the value of an operator boolean allOrNone = one && two; boolean eitherOne = one || two; boolean onlyOne = one ^ two; boolean negated = !one;
p q p && q T T T T F F F T F F F F Boolean ExpressionsTruth Tables • A truth table is a tool we can use to verify the results of a boolean expression for all input values [ Truth Tables on Board ]
Boolean Operators • Precedence • Like arithmetic expressions, boolean expressions can be complex • Like arithmetic expressions, parenthesis can be used to override precedence #1 NOT (!) #2 AND (&&) #3 XOR (^) #4 OR (||) done || found && !interupted (done || found) && !interupted
Advanced Boolean Operations • NAND • !(a && b) • (!a || !b) • NOR • !(a || b) • (!a && !b)
Broadening Our Programming Context • Up till now, we’ve learned: • How to declare primitive variables • ints, doubles, booleans, etc. • How to combine variables, constants, and operators to form complex expressions • Arithmetic Expressions • Boolean Expressions • We can use these to change the value of variables with assignment operators
Review Basic Structure of a Java Program /* Calculator.java Nick Leidenfrost Example program */ public class Calculator { } // this method starts my program public static void main (String[] args) { // statements to be executed here... }
MethodsIntroduction The value resulting from this calculation is our output • Many of us are familiar with the concept of a function from mathematics: • We put in some input • We get some defined output • In general, a method in Java is pretty much the same thing: f(x) = 2x + 5 Here is the expression that uses our input to calculate our output Here is our Input public int calc (int x) { return 2*x + 5; }
MethodsAnatomy The parameter list contains local variable declarations for the input passed into the method. (The name and type of each parameter) The return type defines the type of the output that the method produces. This can be any primitive or object type. The method name can be any identifier we want • Method declarations are composed of 4 main parts: • Method Name • Parameter List • Method Body • Return Type • You may see methods defined with words like “public” and “private” in front of them • These are called access modifiers • You can remain blissfully ignorant of them for another week public int calc (int x) { return 2*x + 5; } Collectively, the name, parameter list, return type and access modifier make up the method signature The method body is enclosed in curly braces ({ and }) and contains an arbitrary number of statements
MethodsDetail: Parameters (Input) • When declaring a method, we can specify any number of parameters that we decide we need: • The parameters can be of any type, and can be named with any legal identifier public int calcY (int x) { return 2*x + 5; } public int calcY (int slope, int x, int yOffset) { return slope*x + yOffset; }
MethodsDetail: Naming & Identifiers • Can two methods have the same name? • Yes, actually. This is known as overloading the method. • The methods can have the same name, but cannot have the same method signature • Why is this useful? • Accepting different types of input to perform a calculation • Specifying default values public int calcY (int x) { return calcY(2, x, 5); }
MethodsDetail: Return Type • The return type of a method specifies what the type of the output will be, e.g. • int, double, boolean, etc. • If a method has no output, it has a return type of void void doSomething () { }
MethodsInvoking / Calling Methods public int calcY (int x) { return 2*x + 5; } The parameters in the method declaration are referred to as the formal parameters • We can execute a method by invoking or calling the method. • To invoke a method, we use the method’s name, and any required input arguments surrounded by parenthesis: • Notice that the formal and actual parameters have the same type • Also, notice how I am using the method as the Right-Hand Side of an assignment operation • This stores the output of the method into the local variable y The arguments passed in when the method is invoked are referred to as the actual parameters int myXVal = 2; int y = calcY(myXVal);
MethodsInvoking / Calling Methods • If a method requires no parameters, we invoke it with just the method name and empty parenthesis int y = generateRandom();
MethodsThe return Statement: Output • The return statement specifies what the output of the method will be • The return statement must evaluate to a type that is assignable (convertible by assignment) to the return type • The Right-Hand Value of the method • Must be the last statement to execute in the method public int calcY (int slope, int x, int yOffset) { int y = slope*x + yOffset; return y; }
MethodsThe return Statement: Output (or lack thereof) • What if a method has a voidreturn type – can it still have a return statement? • Yes, but the return statement cannot include any variable or expression • Can a method with a void return type be used as the Right-Hand side of an assignment? • No. public void calcY (int slope, int x, int yOffset) { int y = slope*x + yOffset; System.out.println(y); return; }
Method Control FlowInvoking Methods & Control Flow • Control flow (or flow of control) is a term that refers to the order of executions of statements within a program • We will learn about many ways of manipulating control flow • Conditional Statements • Loops • When a method is invoked, the flow of control jumps to the method and executes its code • When complete, the flow returns to the place where the method was called and continues • The invocation may or may not return a value, depending on how the method is defined
Sample Program public class CubeANumber { public static void main (String[] args) { int cube; cube = cube(5); System.out.println(cube); } public static int cube (int toCube) { int squared = square(toCube); return toCube*squared; } public static int square (int toSquare) { return toSquare*toSquare; } }
Method Control Flow void main () { int cube (int num) { int square (int num) { square(5); cube(5); } } }
Methods in OOPMethods as Class Members • In Java, all methods are defined within a class definition • Methods define the behavior of the objects of that class • In OOP, methods can be categorized generally as: • Accessors • Retrieve an object’s state (return the value of fields) • Mutators • Manipulate an object’s internal state • Subroutines • Used by other methods in the program – “Helper methods” // You will have 1 of these in Lab 1 // You will have 2 of these in Lab 1 // The rest of the Lab 1 methods
Square Root Method a Sqrt(a) MethodsBenefits: Abstraction • Methods can help support abstraction • The process of hiding detail • Methods specify what inputs it needs (parameters) • Methods specify what outputs it produces (return values) • How it translates the inputs to outputs is hidden from the programmer
MethodsBenefits: Code Reuse • Methods promote code reuse and maintainability • A problem can be solved generally by the method for any input • If we define functionality in one place (inside the method) and need to make a change, we only need to make that change in one place
Lab 1 Overview publicclass Calculator { publicint plus (int a, int b) { return a+b; } // Method Skeleton publicdouble plus (double a, double b) { return 0.0; } }
Lab 1 OverviewReal Programming -> Errors • A program can have three types of errors • Compile-time errors • Syntax and logical errors that can be identified by the compiler. • Prior to execution • Run-time Errors • A problem occurring during program execution, which causes a program to terminate abnormally • Semantic Errors • The program runs, but produces incorrect / undesired results
Lab 1 OverviewEclipse IDE • We will be using the IDE Eclipse for the rest of our labs this semester • You can use another IDE, if you prefer • But I probably won’t know how to use it well…
Lab 1 OverviewMemory Operations • Some methods you are asked to implement, the “memory” operations will require interaction with an instance variable • Instance variables are variables that are defined inside a class body rather than inside a method body • We will learn about these on Tuesday • When we take our next step towards awesomeness: Classes and Objects
Conclusion • Questions? • Lab 1 Assigned • On the website • Due Next Thursday • I will be in Lab now.