Programming Constructs Overview Method calls More selection statements More assignment operators Conditional operator Unary increment and decrement operators Iteration statements Defining methods 27 October 2007 Ariel Shamir 1 Method Call System.out.print( hello ); Is a call to the (static) method print of some class (System.out). The usual syntax is: <classname>.<methodname>(<parameters>); When you are inside the same class as the method called, there is no need to use the class name. 27 October 2007 Ariel Shamir 2 Method Parameters If the method requires parameters, they come inside the parentheses as a list. The order and type of parameters must be the same as required by the method. System.out.println(... ) Requires one parameter of type String. 27 October 2007 Ariel Shamir 3 1
Math Methods double d1, d2, d3, d4, d5; d2 = 99.7; d1 = Math.ceil(d2); d3 = Math.sqrt(d1); d4 = Math.sin(Math.PI*2); d5 = Math.min(d1,d3); 27 October 2007 Ariel Shamir 4 Statements We Know int number = 0; // declaration statement number = 25; // assignment statement System.out.println( hello ); // method call int i = myscanner.nextint(); //? 27 October 2007 Ariel Shamir 5 Control Structures and Statements There are several types of statements: Declaration statements Assignment statement Method call statement Expression statements Iteration statements Selection statements Control flow statements 27 October 2007 Ariel Shamir 6 2
Control Flow Statements The control structures affect the flow of control in a program. Control flow statements can be divided into two types: selection statements iteration statements if switch for while do while 27 October 2007 Ariel Shamir 7 If & If..Else Statements statement statement false If? true statement true If..else? false statement statement statement statement 27 October 2007 Ariel Shamir 8 Switch Statement The switch statement is a choice between doing several things (usually more then two things). The switch statement evaluates an expression, then attempts to match the result to one of a series of values. Execution transfers to statement list associated with the first value that matches. 27 October 2007 Ariel Shamir 9 3
Switch Syntax switch(exp){ case value1: statement1; break; case valuen: statementn; break; default: defaultstatement; break; 27 October 2007 Ariel Shamir 10 Choice of Execution If the value of exp equals to value1 then statement1 is performed. If the value of exp equals to valuen then statementn is performed. If the value of exp is different from value1,..., valuen then defaultstatement is performed. 27 October 2007 Ariel Shamir 11 Switch Statement Details exp can be an integer variable or an expression that evaluate to an integer value. statementn can be empty or can be a set of instructions. A default case can be added to the end of the list of cases, and will execute if no other case matches. 27 October 2007 Ariel Shamir 12 4
The Break Statement The break statement is usually used to terminate the statement list of each case. This causes the control to jump to the end of the switch statement and continue. Note: if the break statement is omitted execution continues ( falls ) to the next case! 27 October 2007 Ariel Shamir 13 Example switch(item) { case 0: case 1: // do something break; default: // do something break; case 2: // do something break; case 8: // do something break; 27 October 2007 Ariel Shamir 14 Example switch(letter) { case a : System.out.println( The letter was a ); add(); break; case d : System.out.println( The letter was d ); delete(); break; default: System.out.println( Illegal input ); break; 27 October 2007 Ariel Shamir 15 5
More Operators Conditional (ternary? : ) Assignment (binary += ) Increment & decrement (unary ++) 27 October 2007 Ariel Shamir 16 The Conditional Operator The conditional operator evaluates a Boolean condition that determines which of two expressions is evaluated. condition? exp1 : exp2 If condition is true, exp1 is evaluated; if it is false, exp2 is evaluated. The result of the chosen expression is the result of the entire conditional operator. 27 October 2007 Ariel Shamir 17 Conditional Operator Usage The conditional operator is similar to an if-else statement, except that it is an expression that returns a value: int max = (a > b)? a : b; If a is greater that b, then a is assigned to max; otherwise, b is assigned to max. The conditional operator is ternary, meaning it requires three operands 27 October 2007 Ariel Shamir 18 6
Conditional Operator Example System.out.println ("Your change is " + count + ((count == 1)? Shekel" : " Shekels )); If count equals 1, Shekel" is printed, otherwise Shekels" is printed The conditional operator can be nested: int max = (a > b)? ((a > c)? a : c) : ((b > c)? b : c) ; 27 October 2007 Ariel Shamir 19 More Assignment Operators Often we perform an operation on a variable, then store the result back into that variable. Java provides assignment operators that do just this. Instead of : sum = sum + value; you can write: sum += value; 27 October 2007 Ariel Shamir 20 Assignment Operators List Operator += -= *= /= %= = &= Example x += y; x -= y; x *= y; x /= y; x %= y; x = y; x &= y; Equivalent To x = x + y; x = x y; x = x * y; x = x / y; x = x % y; x = x y; x = x & y; 27 October 2007 Ariel Shamir 21 7
Right Hand Side Expression The right hand side of an assignment operator can be a complete expression. The entire right-hand expression is evaluated first, then combined with the additional operation. result /= (total-min) % n; is NOT equivalent to: result = result/(total-min) % n; but equivalent to result = result / ((total-min) % n); 27 October 2007 Ariel Shamir 22 Unary Increment and Decrement Operators The ++ and -- are the increment and decrement operators. For example the expression j++ is equivalent to j=j+1. The increment and decrement operators can be used as: Prefix appears before what they operate on. Postfix appears after what they operate on. 27 October 2007 Ariel Shamir 23 Increment, Decrement Operators Usage Operator Use Description ++ ++ -- -- j++ ++j j-- --j evaluates to the value of j before it was incremented increments j by 1 increments j by 1 evaluates to the value of j after it was incremented evaluates to the value of j before it was decremented decrements j by 1 decrements j by 1 evaluates to the value of j after it was decremented 27 October 2007 Ariel Shamir 24 8
Inc/Dec Example class IncDecExample { public static void main(string args[]) { int i0,i1,i2,j=5; i0 = ++j; i1 = j++; i2 = j--; System.out.println(i0+ +i1 + +i2); 27 October 2007 Ariel Shamir 25 Inc/Dec Example (Cont) The output is: 6 6 7 i0 = ++j; j is pre-incremented to 6 and assigned to i0. i1 = j++; j is first assigned to i1 (as 6) and then post-incremented to 7. i2 = j--; j with a value of 7 is assigned to i2 and then post-decremented to 6. 27 October 2007 Ariel Shamir 26 More Control Flow What if we want to repeat some sequence of statements many times? statement statement statement statement 27 October 2007 Ariel Shamir 27 9
Iteration Statements Iteration statements are also called loop control structures. A loop is a repetition of certain pieces of the code several times. In Java there are Three types of Loops: for loop, while loop, do loop. 27 October 2007 Ariel Shamir 28 For Statement for( start; limit; step_exp) { statement; start is a statement that initializes the loop. limit is a Boolean statement that determines when to terminate the loop. It is evaluated before each iteration. 27 October 2007 Ariel Shamir 29 For Statement (Cont.) When limit is true statement is performed, when it is false the loop is terminated. step_exp is an expression that is invoked after each iteration of the loop and is called the step of the loop. The for loop is often used for counting from start to limit by a step size. 27 October 2007 Ariel Shamir 30 10
For Diagram Start Limit Condition true false Statement Step 27 October 2007 Ariel Shamir 31 For Example class For_Example { public static void main(string[] args){ int fact = 1; for(int k=1; k<5; k++) { fact *= k; System.out.println( The factorial of + k + is: + fact); 27 October 2007 Ariel Shamir 32 While Statement while( Boolean_cond) statement; The value of Boolean_cond can be: true and than the statement is performed false and than loop terminates The statement is executed over and over until the boolean_condition becomes false. 27 October 2007 Ariel Shamir 33 11
While Diagram Boolean Condition false true Statement 27 October 2007 Ariel Shamir 34 While Example class While_Example { public static void main(string[] args){ int sum=0,k=0; while(sum<100) { sum=sum+k; System.out.print( the sum of 0 to + k + is + sum); k++; 27 October 2007 Ariel Shamir 35 Do.. While Statement do { statement; while (Boolean_cond); First, the statement performed once! Then, the Boolean_cond is checked. If it is true the next iteration of the loop is performed. If it is false, the loop terminates. 27 October 2007 Ariel Shamir 36 12
Do.. While Diagram Statement true Boolean Condition false 27 October 2007 Ariel Shamir 37 Infinite Loops If Boolean_cond in one of the loop structures is always true then loop will be executed forever - it is unbounded. Such a loop is called an infinite loop. The infinite loop will execute until the program is interrupted. 27 October 2007 Ariel Shamir 38 Infinite Loop Example // Two infinite loops program Class Infinity { public static void main(string[] args){ int count=0; for( ; ; ) System.out.print( Infinity ); while(count<10) { System.out.println( Another infinite loop ); System.out.println( The counter is +counter); 27 October 2007 Ariel Shamir 39 13
Nested Loops Example for (int row = 1; row <= numrows; row++) { for (int column = 1; column <= numcolumns; column++) { System.out.print(row * column + ); System.out.println(); Can you make this code more efficient? 27 October 2007 Ariel Shamir 40 Break inside a Loop The break statement, (already used within the switch statement), can also be used inside a loop When the break statement is executed, control jumps to the statement after the loop (the condition is not evaluated again) 27 October 2007 Ariel Shamir 41 Continue inside a Loop A similar statement to the break is continue inside loops When the continue statement is executed, control jumps to the end of the loop and the condition is evaluated (possibly entering the loop statements again) 27 October 2007 Ariel Shamir 42 14
Break and Continue Example for (;;) { Scanner sc = new Scanner(System.in); int n = sc.nextint(); if (n == 0) break; if (n%2 == 1) continue; sum += n; System.out.print( Can you modify it to get rid of the break and continue? The sum of all input even numbers is + sum); 27 October 2007 Ariel Shamir 43 Division Into Methods Complicated tasks or tasks that occur often within a class should be wrapped in a method It is helpful when implementing algorithms, or when we need helper methods in classes. This will increase the readability and manageability of the code 27 October 2007 Ariel Shamir 44 Sub Tasks Example Task: calculate & print the average and median of all students: Get the grades of a student Calculate the average Calculate the median Outer Loop On Students Inner Loops On Grades 27 October 2007 Ariel Shamir 45 15
Sub Tasks Example Task: calculate & print the average and median of all students: Get the grades of a student Calculate the average Calculate the median Outer Loop On Students Define as methods 27 October 2007 Ariel Shamir 46 Defining Methods Simplify and structure the program code using sub-tasks Reuse of the same piece of code (the method) in many places 27 October 2007 Ariel Shamir 47 Example 1: Finding Primes // Prints all the prime numbers in a range public class Primes { public static final int RANGE = 1000; public static void main(string[] args) { int number = 0; while (number < RANGE) { number = number + 1; for (int n = 0 ; n < number ; n++) { //...check if n divides number... 27 October 2007 Ariel Shamir 48 16
Example 1 (Cont.) // Prints all the prime numbers in a range public class Primes { public static final int RANGE = 1000; public static void main(string[] args) { int number = 0; while (number < RANGE) { number = number + 1; if (isprime(number)) out.println(number); 27 October 2007 Ariel Shamir 49 Example 1 (Cont.) // Prints all the prime numbers in a range public class Primes { public static void main(string[] args) { //... if (isprime(number)) //... // Returns true iff number is prime public static boolean isprime(int number) { // determines if number is prime 27 October 2007 Ariel Shamir 50 Example 2: Magic Number A magic number is a number who s sum of cubes of digits equals itself: XYZ = X 3 + Y 3 + Z 3 Finding all magic numbers in the range 1-M: For each n in the range 1-M: Compute the sum of cubes of digits of n Check if this sum equals n 27 October 2007 Ariel Shamir 51 17
SumofCubes Method Finding all magic numbers in the range 1-M: For each n in the range 1-M: Compute the sum of cubes of digits of n Check if this sum equals n /** * Returns the sum of cubes of digits of n */ static int sumofcubesofdigits(int n) { // 27 October 2007 Ariel Shamir 52 Method Header We declare methods in a similar way to the way the method main was declared: public static void main(string[] args) { // the code public static double average(int num1,int num2) { // the code return type name parameters 27 October 2007 Ariel Shamir 53 Methods Modifiers The modifier public denotes that the method is exposes to outside world (more on this later) The modifier static denotes that this method can be called without creating an object of this type (more on this too, later) 27 October 2007 Ariel Shamir 54 18
Return Types The return type of a method indicates the type of value that the method sends back to the calling client. The return-type of average() is double. When a client calls the method average() it will get the answer as a double value. The keyword void denotes that the method has no return value (main()) 27 October 2007 Ariel Shamir 55 Method Return Types public static double average(int num1,int num2) {... public static int sumofcubesofdigits(int n) {... public static boolean isprime(int number) {... public static void main(string[] args) {... 27 October 2007 Ariel Shamir 56 Return Statement return <expression>; In the method definition, the return statement specifies the value that should be returned, which must conform with the return type of the method. If the method returns void you can just use return; or you can omit the statement (and reach the end of all the method statements) 27 October 2007 Ariel Shamir 57 19
Using the Return Value double avg; // more code avg = average(33,56); The parameters sent to average It will return a value which is assigned to avg The average method will be invoked 27 October 2007 Ariel Shamir 58 Method Parameters To invoke a method you must use the correct 1. Number of parameters 2. Type of parameters 3. Order of parameters Sometimes there are several methods with the same name be careful! 27 October 2007 Ariel Shamir 59 Passing Parameters When a parameter is passed, a copy of the value is made and assigned to the formal parameter: double avg; avg = average(33,56); public static double average(int num1,int num2) 27 October 2007 Ariel Shamir 60 20
Code Example Parameters can be used as any other variable The return expression must match the return type public static double average(int num1,int num2) { return (num1 + num2)/2.0; 27 October 2007 Ariel Shamir 61 Method control flow Instead of writing a long list of instructions we write a collection of methods and invoke (or call) them one after another. main() Main invokes M1 M1 invokes M2 Main invokes M1()... M2() 27 October 2007 Ariel Shamir 62 Control Flow Chart We decomposed a problem into series of simpler methods. The invoked method could be part of another class or object. main M1 M2 obj.m1(); M2(); 27 October 2007 Ariel Shamir 63 21
The Random Class A program may need to produce a random number (DiceSimulation.java). The Random class provides methods to simulate a random number generator. The nextint method returns a random number from the entire spectrum of int values. Usually, this number is be scaled and shifted to the desired range. 27 October 2007 Ariel Shamir 64 Random Class Example import java.util.random; // This program simulates a tossing of a dice class DiceSimulation { static final int NUMBER_OF_TOSSES = 10; public static void main(string[] args) { int sum = 0; int count = 0; Random rndgen = new Random(); 27 October 2007 Ariel Shamir 65 Random Class Example while(count<=number_of_tosses) { int result = Math.abs(rndGen.nextInt())%6+1; sum = sum + result; count = count + 1; System.out.println( The sum of tosses is +sum); 27 October 2007 Ariel Shamir 66 22