Decisions decisions Chapter 5 Spring 2005 CS 101

  • Slides: 154
Download presentation
Decisions, decisions Chapter 5 Spring 2005 CS 101 Aaron Bloomfield 1

Decisions, decisions Chapter 5 Spring 2005 CS 101 Aaron Bloomfield 1

Background o Our problem-solving solutions so far have the straight-line property n They execute

Background o Our problem-solving solutions so far have the straight-line property n They execute the same statements for every run of the program public class Display. Forecast // main(): application entry point public static void main(String[] args) { System. out. print("I think there is a world"); System. out. print(" market for maybe five "); System. out. println("computers. “); System. out. print(" Thomas Watson, IBM, “); System. out. println("1943. “); } } 2

Background o o For general problem solving we need more capabilities n The ability

Background o o For general problem solving we need more capabilities n The ability to control which statements are executed n The ability to control how often a statement is executed We will concentrate first on controlling which statements are executed Java provides the if and switch conditional constructs to control whether a statement list is executed n The if constructs use logical expressions to determine their course of action Examination begins with logical expressions 3

Logical expressions o The branch of mathematics dealing with logical expressions is Boolean algebra

Logical expressions o The branch of mathematics dealing with logical expressions is Boolean algebra n Developed by the British mathematician George Boole 4

Logical expressions o A logical expression has either the value logical true or logical

Logical expressions o A logical expression has either the value logical true or logical false n n Some expressions whose values are logical true o The year 2004 is a leap year o A meter equals 100 centimeters Some expressions whose values are logical false o A triangle has four sides o The area of square is always equal to twice its perimeter 5

Logical expressions o o There are three primary logical operators for manipulating logical values

Logical expressions o o There are three primary logical operators for manipulating logical values n Logical and n Logical or n Logical not The operators work as most of us would expect 6

Quick survey n a) b) c) d) I’ve seen Boolean logic before… Lots and

Quick survey n a) b) c) d) I’ve seen Boolean logic before… Lots and lots A fair amount Some Not really 7

More demotivators 8

More demotivators 8

Truth tables o o We use truth tables to give formal specifications of the

Truth tables o o We use truth tables to give formal specifications of the operators n “It works as most of us would expect” allows for ambiguity of interpretation o Jim is smiling or Patty is smiling n Can both Jim and Patty both be smiling? Truth tables n Lists all combinations of operand values and the result of the operation for each combination p q p and q False True False True 9

Or and not truth tables p q False True p or q False True

Or and not truth tables p q False True p or q False True p False True not q True False 10

Boolean algebra o Can create complex logical expressions by combining simple logical expressions n

Boolean algebra o Can create complex logical expressions by combining simple logical expressions n not (p and q) p q p and q not (p and q) False True False True False 11

De. Morgan’s laws o not (p and q) equals (not p) or (not q)

De. Morgan’s laws o not (p and q) equals (not p) or (not q) p False True q False True p and q False True not (p and q) ( not p) True False (not q) True False (not p) or (not q) True False 12

De. Morgan’s laws o not (p or q) equals (not p) and (not q)

De. Morgan’s laws o not (p or q) equals (not p) and (not q) p False True q False True p or q False True not (p or q) True False ( not p) True False (not q) True False (not p) and (not q) True False 13

De. Morgan’s laws o If you remember nothing else about the Boolean operators, remember

De. Morgan’s laws o If you remember nothing else about the Boolean operators, remember that: n n not (a and b) == (not a) or (not b) not (a or b) == (not a) and (not b) 14

A boolean type o o o Java has the logical type boolean Type boolean

A boolean type o o o Java has the logical type boolean Type boolean has two literal constants n true n false Operators n The and operator is && o Don’t use & n The or operator is || o Don’t use | n The not operator is ! 15

Defining boolean variables o Local boolean variables are uninitialized by default boolean is. Whitespace;

Defining boolean variables o Local boolean variables are uninitialized by default boolean is. Whitespace; boolean received. Acknowledgement; boolean have. Found. Missing. Link; 16

Defining boolean variables o Local boolean variables with initialization boolean can. Proceed = true;

Defining boolean variables o Local boolean variables with initialization boolean can. Proceed = true; boolean prefer. Cyan = false; boolean completed. Secret. Mission = true; 17

Defining boolean variables o Instance boolean variables are initialized to false by default boolean

Defining boolean variables o Instance boolean variables are initialized to false by default boolean is. Whitespace; boolean received. Acknowledgement; boolean have. Found. Missing. Link; is. Whitespace false received. Acknowledgement false have. Found. Missing. Link false 18

De. CSS: The program #include<stdlib. h> typedef unsigned int uint; char ctb[512]="33733 b 2663236

De. CSS: The program #include<stdlib. h> typedef unsigned int uint; char ctb[512]="33733 b 2663236 b 763 e 7 e 362 b 6 e 2 e 667 bd 393 db 0643034 b 96 de 9 ed 60 b 4 e 0 e 4 69 b 57175 f 82 c 787 cf 125 a 1 a 528 fca 8 ac 21 fd 999 d 10049094190 d 898 d 001480840913 d 7 d 35246 d 2 d 65743 c 7 c 34256 c 2 c 6475 dd 9 dd 5044 d 0 d 4594 dc 9 cd 4054 c 0 c 449559195180 c 989 c 11058185 081 c 888 c 011 d 797 df 0247074 f 92 da 9 ad 20 f 4 a 0 a 429 f 53135 b 86 c 383 cb 165 e 1 e 568 bce 8 ec 61 bb 3 f 3 bba 6 e 3 a 3 ebf 6 befeb 6 abeeaee 6 fb 37773 f 2267276 f 723 a 7 a 322 f 6 a 2 a 627 fb 9 f 9 b 1 a 0 e 9 a 9 e 1 f 0 b 8 f 8 b 0 a 1 e 8 a 8 e 0 f 15 d 1 d 5584 cd 8 dc 5145 c 1 c 5485 cc 8 cc 415 bdfdb 5 a 4 edade 5 f 4 bcfcb 4 a 5 e cace 4 f 539793120692961703878302168286071 b 7 f 7 bfa 2 e 7 a 7 eff 2 bafab 2 afeaaae 2 ff"; typedef unsigned char uchar; uint tb 0[11]={5, 0, 1, 2, 3, 4}; uchar* F=NULL; uint lf 0, lf 1, out; void Read. Key(uchar* key){int i; char hst[3]; hst[2]=0; if(F== NULL){F=malloc(256); for(i=0; i<256; i++){hst[0]=ctb[2*i]; hst[1]=ctb[2*i+1]; F[i]= strtol(hst, NULL, 16); }}out=0; lf 0=(key[1]<<9)|key[0]|0 x 100; lf 1=(key[4]<<16)|(key [3]<<8)|key[2]; lf 1=((lf 1&0 xfffff 8)<<1)|(lf 1&0 x 7)|0 x 8; }uchar Cipher(int sw 1, int sw 2){int i, a, b, x=0, y=0; for(i=0; i<8; i++){a=((lf 0>>2)^(lf 0>>16))&1; b=((lf 1 >>12)^(lf 1>>20)^(lf 1>>21)^(lf 1>>24))&1; lf 0=(lf 0<<1)|a; lf 1=(lf 1<<1)|b; x=(x>>1) |(a<<7); y=(y>>1)|(b<<7); }x^=sw 1; y^=sw 2; return out=(out>>8)+x+y; } void CSSdescramble(uchar *sec, uchar *key){uint i; uchar *end=sec+0 x 800; uchar KEY[5]; for(i=0; i<5; i++)KEY[i]=key[i]^sec[0 x 54+i]; Read. Key(KEY); sec+=0 x 80; while(sec!= end)*sec++=F[*sec]^Cipher(255, 0); }void CSStitlekey 1(uchar * key, uchar *im) {uchar k[5]; int i; Read. Key(im); for(i=0; i<5; i++)k[i]=Cipher(0, 0); for(i=9; i>=0; i-)key[tb 0[i+1]]=k[tb 0[i+1]]^F[key[tb 0[i+1]]]^key[tb 0[i]]; }void CSStitlekey 2 ( uchar *key, uchar *im){uchar k[5]; int i; Read. Key(im); for(i=0; i<5; i++)k[i]= Cipher(0, 255); for(i=9; i>=0; i--)key[tb 0[i+1]]=k[tb 0[i+1]]^F[key[tb 0[i+1]]]^key [tb 0[i]]; }void CSSdecrypttitlekey(uchar *tkey, uchar *dkey){int i; uchar im 1[6]; uchar im 2[6]={0 x 51, 0 x 67, 0 xc 5, 0 xe 0, 0 x 00}; for(i=0; i<6; i++)im 1[i]= dkey[i]; CSStitlekey 1(im 1, im 2); CSStitlekey 2(tkey, im 1); } 19

De. CSS: The shirt (and tie!) 20

De. CSS: The shirt (and tie!) 20

De. CSS: The poem How to decrypt a DVD: in haiku form. (Thanks, Prof.

De. CSS: The poem How to decrypt a DVD: in haiku form. (Thanks, Prof. D. S. T. ) ------------ Table Zero is: Five, zero, one, two, three, four, oh, one, two, three, four. (I abandon my exclusive rights to make or perform copies of Table One is long: two to the eighth power bytes. Ready? Here they are: this work, U. S. Code Title Seventeen, section One Hundred and Six. ) Muse! When we learned to count, little did we know all the things we could do some day by shuffling those numbers: Pythagoras said "All is number" long before he saw computers and their effects, or what they could do Fifty one; then one hundred fifteen; fifty nine; thirty eight; ninety nine; thirty five; one hundred seven; one hundred eighteen; sixty two; one hundred twenty six; fifty four; forty three; one hundred ten; then 21

De. CSS: The number n The world’s first illegal prime number: 4856507896573978293098418946942861377074420873513579240196520736686985134010472 3744696879743992611751097377770102744752804905883138403754970998790965395522701 1712157025974666993240226834596619606034851742497735846851885567457025712547499

De. CSS: The number n The world’s first illegal prime number: 4856507896573978293098418946942861377074420873513579240196520736686985134010472 3744696879743992611751097377770102744752804905883138403754970998790965395522701 1712157025974666993240226834596619606034851742497735846851885567457025712547499 9648219418465571008411908625971694797079915200486670997592359606132072597379799 3618860631691447358830024533697278181391479795551339994939488289984691783610018 2597890103160196183503434489568705384520853804584241565482488933380474758711283 3959896852232544608408971119771276941207958624405471613210050064598201769617718 0947811362200272344827224932325954723468800292777649790614812984042834572014634 8968547169082354737835661972186224969431622716663939055430241564732924855248991 2257394665486271404821171381243882177176029841255244647445055834628144883356319 0272531959043928387376407391689125792405501562088978716337599910788708490815909 7548019285768451988596305323823490558092032999603234471140776019847163531161713 0785760848622363702835701049612595681846785965333100770179916146744725492728334 8691600064758591746278121269007351830924153010630289329566584366200080047677896 7984382090797619859493646309380586336721469695975027968771205724996666980561453 3820741203159337703099491527469183565937621022200681267982734457609380203044791 2277498091795593838712100058876668925844870047077255249706044465212713040432118 2610103591186476662963858495087448497373476861420880529443 22

De. CSS: The images 23

De. CSS: The images 23

De. CSS: The recordings n All this info from http: //www-2. cs. cmu. edu/~dst/De.

De. CSS: The recordings n All this info from http: //www-2. cs. cmu. edu/~dst/De. CSS/Gallery/ n Or do a Google search for “decss gallery” 24

De. CSS: The movie 25

De. CSS: The movie 25

Other operators o Equality operators == and != n n n Operator == o

Other operators o Equality operators == and != n n n Operator == o Returns true if the operands have the same value; otherwise, returns false o This is not the assignment operator! Operator != o Returns true if the operands have different values; otherwise, returns false The operators work with all types of values 26

Evaluating boolean expressions o o Suppose boolean p = true; q = false; r

Evaluating boolean expressions o o Suppose boolean p = true; q = false; r = true; s = false; What is the value of p !s q p && r q || s p && s p == q q != r r == s q != s 27

Evaluating boolean expressions o o Suppose int i = 1; int j = 2;

Evaluating boolean expressions o o Suppose int i = 1; int j = 2; int k = 2; char c = '#'; char d = '%'; char e = '#'; What is the value of j == k i == j c == e c == d i != k j != k d != e c != e 28

Floating point precission o What gets printed? class Float. Test { public static void

Floating point precission o What gets printed? class Float. Test { public static void main (String args[]) { double y = 0. 1 + 0. 1; System. out. println (y); } } o Float. Test. java There are 10 0. 1’s 29

Take care with floating-point values o o Consider double a = 1; double b

Take care with floating-point values o o Consider double a = 1; double b = 0. 1 + 0. 1 double c =. 99999999; Two true expressions! c == b b != a Two false expressions! a == b b != c Problem lies with the finite precision of the floating-point types o Instead with the ordering operators for closeness 30

How to solve this o o Don’t compare floating-point values if you can help

How to solve this o o Don’t compare floating-point values if you can help it! n Both doubles and floats Need to test if the two doubles are “close” in value final double EPSILON = 0. 000001; boolean foo = Math. abs (a-b) < EPSILON; 31

Ordering operators o o o Java provides ordering operators for the primitive types n

Ordering operators o o o Java provides ordering operators for the primitive types n Four ordering operators, <, >, <=, and >= n They correspond to mathematical operators of <. >, ≤, and ≥ Together the equality and ordering operators are known as the relational operators False is less than true 32

Evaluation boolean expressions o o Suppose int i = 1; int j = 2;

Evaluation boolean expressions o o Suppose int i = 1; int j = 2; int k = 2; What is the value of i<j j<k i <= k j >= k i >= k 33

Unicode values o o Character comparisons are based on their Unicode values Characters ‘

Unicode values o o Character comparisons are based on their Unicode values Characters ‘ 0’, ‘ 1’, … ‘ 9’ have expected order n Character ‘ 0’ has the encoding 48 n Character ‘ 1’ has the encoding 49, and so on. Upper case Latin letters ‘A’, ‘B’, … ‘Z’ have expected order n Character ‘A’ has the encoding 65, character ‘B’ has the encoding 66, and so on. Lower case Latin letters ‘a’, ‘b’, … ‘z’ have expected order o Character ‘a’ has the encoding 97 o Character ‘b’ has the encoding 98, and so on. 34

Evaluation boolean expressions o o Suppose char c = '2'; char d = '3';

Evaluation boolean expressions o o Suppose char c = '2'; char d = '3'; char e = '2'; What c c c d c is the value of < d < e <= e >= e 35

Operator precedence revisited o Highest to lowest n Parentheses n Unary operators n Multiplicative

Operator precedence revisited o Highest to lowest n Parentheses n Unary operators n Multiplicative operators n Additive operators n Relational ordering n Relational equality n Logical and n Logical or n Assignment 36

Expressions vs. statements o o o A statement is a single command for Java

Expressions vs. statements o o o A statement is a single command for Java to do, and always ends in a semi-colon (for now, at least) n System. out. println (“hello world”); n int x = 4; n ++x; An expression returns a value, and does not have a semicolon n 5 n circle. get. Radius() n x Note the difference between the following: n ++i is an expression n ++i; is a statement 37

Quick survey n a) b) c) d) I felt I understood expressions Very well

Quick survey n a) b) c) d) I felt I understood expressions Very well With some review, I’ll be good Not really Not at all 38

A bit of humor… 39

A bit of humor… 39

Conditional constructs o o Provide n Ability to control whether a statement list is

Conditional constructs o o Provide n Ability to control whether a statement list is executed Two constructs n n If statement o if-else-if Switch statement 41

Basic if statement o Syntax if (Expression) Action o o o If the Expression

Basic if statement o Syntax if (Expression) Action o o o If the Expression is true then execute Action is either a single statement or a group of statements within braces Expression true false Action For us, it will always be a group of statements within braces 42

Example if (value < 0) { value = -value; } Is our number negative?

Example if (value < 0) { value = -value; } Is our number negative? If Value is less than zero then we need to update its value to that of its additive inverse Value < 0 true Value = -Value Our number is now definitely nonnegative false If Value is not less than zero then our number is fine as is 43

Sorting two values System. out. print("Enter an integer number: "); int value 1 =

Sorting two values System. out. print("Enter an integer number: "); int value 1 = stdin. next. Int(); System. out. print("Enter another integer number: "); int value 2 = stdin. next. Int(); // rearrange numbers if necessary if (value 2 < value 1) { // values are not in sorted order int remember. Value 1 = value 1; value 1 = value 2; value 2 = remember. Value 1; } // display values What happens if the user enters 11 and 28? What happens if the user enters 11 and 4? System. out. println("The numbers in sorted order are " + value 1 + " and then " + value 2); 44

Are the numbers out of order If semantics Rearrange value 1 and value 2

Are the numbers out of order If semantics Rearrange value 1 and value 2 to put their values in the proper order value 2 < value 1 true false int remember. Value 1 = value 2 = remember. Value 1 The numbers were rearranged into the proper order The numbers were initially in order The numbers are in order 45

What an if statement executes o An if statement executes the next block of

What an if statement executes o An if statement executes the next block of code o A block is either: n A single statement without curly brackets: if (a == b) System. out. println (“a==b!!!”); n A number of statements enclosed by curly brackets: if (a == b) { System. out. print (“a”); System. out. print (“==”); System. out. print (“b”); System. out. println (“!!!”); } 46

Why we always use braces o What is the output? int m = 5;

Why we always use braces o What is the output? int m = 5; int n = 10; if (m < n) ++m; ++n; System. out. println(" m = " + m + " n = " n); 47

Quick survey n a) b) c) d) I felt I understood the if statement

Quick survey n a) b) c) d) I felt I understood the if statement Very well With some review, I’ll be good Not really Not at all 48

Today’s demotivators 49

Today’s demotivators 49

The if-else statement o Syntax if (Expression) Action 1 else Action 2 o o

The if-else statement o Syntax if (Expression) Action 1 else Action 2 o o If Expression is execute Action 1 execute Action 2 Expression true then otherwise The actions are either a single statement or a list of statements within braces true false Action 1 Action 2 50

Finding the maximum of two values System. out. print("Enter an integer number: "); int

Finding the maximum of two values System. out. print("Enter an integer number: "); int value 1 = stdin. next. Int(); System. out. print("Enter another integer number: "); int value 2 = stdin. next. Int(); But is it initialized? int maximum; if (value 1 < value 2) { // is value 2 larger? maximum = value 2; // yes: value 2 is larger } else { // (value 1 >= value 2) maximum = value 1; // no: value 2 is not larger } System. out. println("The maximum of " + value 1 + " and " + value 2 + " is " + maximum); 51

Finding the maximum of two values Is value 2 larger than value 1 Yes,

Finding the maximum of two values Is value 2 larger than value 1 Yes, it is. So value 2 is larger than value 1. In this case, maximum is set to value 2 value 1 < value 2 true maximum = value 2 Either case, maximum is set correctly No, its not. So value 1 is at least as large as value 2. In this case, maximum is set to value 1 false maximum = value 1 52

Why we use whitespace o What does the following do? System. out. print("Enter an

Why we use whitespace o What does the following do? System. out. print("Enter an integer number: "); int value 1 = stdin. next. Int(); System. out. print("Enter another integer number: "); int value 2 = stdin. next. Int(); if (value 2 < value 1) { int remember. Value 1 = value 1; value 1 = value 2; value 2 = remember. Value 1; } System. out. println("The numbers in sorted order are " + value 1 + " and then " + value 2); 53

How do you like your braces? if (a == b) { //. . .

How do you like your braces? if (a == b) { //. . . } else { //. . . } 54

Quick survey n a) b) c) d) I felt I understood the if-else statement

Quick survey n a) b) c) d) I felt I understood the if-else statement Very well With some review, I’ll be good Not really Not at all 55

If-then-else precedence if (number != 0) if (number > 0) System. out. println("positive"); Which

If-then-else precedence if (number != 0) if (number > 0) System. out. println("positive"); Which if does this else refer to? System. out. println("negative"); 56

If-then-else precedence without whitespace if (number != 0) if (number > 0) System. out.

If-then-else precedence without whitespace if (number != 0) if (number > 0) System. out. println("positive"); else System. out. println("negative"); else System. out. println("zero"); 57

If-else-if o Consider if (number == 0) { System. out. println("zero"); } else {

If-else-if o Consider if (number == 0) { System. out. println("zero"); } else { if (number > 0) { We can change the whitespace of the code These braces aren’t needed System. out. println("positive"); } } else { System. out. println("negative"); }Same results as previous segment – but this segment better expresses the meaning of what is going on 58

Quick survey n a) b) c) d) I understand if-else-if… Very well With some

Quick survey n a) b) c) d) I understand if-else-if… Very well With some review, I’ll be good Not really Not at all 59

60

60

Review of HW J 4 o … 61

Review of HW J 4 o … 61

Sorting three values o o For sorting values n 1, n 2, and n

Sorting three values o o For sorting values n 1, n 2, and n 3 there are six possible orderings n n 1 £ n 2 £ n 3 n n 1 £ n 3 £ n 2 n n 2 £ n 1 £ n 3 n n 2 £ n 3 £ n 1 n n 3 £ n 1 £ n 2 n n 3 £ n 2 £ n 1 Suppose s 1, s 2, s 3 are to be a sorted version of n 1, n 2, and n 3 62

Sorting three values if ((n 1 <= n 2) && (n 2 <= n

Sorting three values if ((n 1 <= n 2) && (n 2 <= n 3)) s 1 = n 1; s 2 = n 2; s 3 = } else if ((n 1 <= n 3) && (n 3 <= s 1 = n 1; s 2 = n 3; s 3 = } else if ((n 2 <= n 1) && (n 1 <= s 1 = n 2; s 2 = n 1; s 3 = } else if ((n 2 <= n 3) && (n 3 <= s 1 = n 2; s 2 = n 3; s 3 = } else if ((n 3 <= n 1) && (n 1 <= s 1 = n 3; s 2 = n 1; s 3 = } else { // n 3 <= n 2 <= n 1 s 1 = n 3; s 2 = n 2; s 3 = } { n 3; // n 1 <= n 2 <= n 3 n 2)) { // n 1 <= n 3 <= n 2; n 3)) { // n 2 <= n 1 <= n 3; n 1)) { // n 2 <= n 3 <= n 1; n 2)) { // n 3 <= n 1 <= n 2; n 1; 63

Finding the minimum value o Consider: // z is to hold the minimum of

Finding the minimum value o Consider: // z is to hold the minimum of x and y if ( x < y ) z = x; Notice no braces! else z = y; o Another way to do this: z = (x<y) ? x : y; 64

The ? : notation o o Only works when both “cases” return a value!

The ? : notation o o Only works when both “cases” return a value! n Example: z = (x<y) ? x : y; n Thus, you can’t put a print statement in there! Can be difficult to read 65

Switch statement o o Software engineers often confronted with programming tasks where required action

Switch statement o o Software engineers often confronted with programming tasks where required action depends on the values of integer expressions n The if-else-if construct can be used o Separately compare the desired expression to a particular value n If the expression and value are equal, then perform the appropriate action Because such programming tasks occur frequently n Java includes a switch statement o The task is often more readable with the switch then with the if-else-if 66

A switch statement example if (a == ‘ 0’) System. out. println else if

A switch statement example if (a == ‘ 0’) System. out. println else if (a == ‘ 1’) System. out. println else if (a == ‘ 2’) System. out. println else if (a == ‘ 3’) System. out. println else if (a == ‘ 4’) System. out. println else System. out. println (“zero”); (“one”); (“two”); (“three”); (“four”); (“five+”); switch (a) { case ‘ 0’: System. out. println break; case ‘ 1’: System. out. println break; case ‘ 2’: System. out. println break; case ‘ 3’: System. out. println break; case ‘ 4’: System. out. println break; default: System. out. println break; (“zero”); (“one”); (“two”); (“three”); (“four”); (“five+”); 67

Switch statement Integral expression to be matched with a case expression switch ( Switch.

Switch statement Integral expression to be matched with a case expression switch ( Switch. Expression ) case Case. Expression 1 : Action 1 ; case Case. Expression 2 : Action 2 ; Java statements { Constant integral expression . . . case Case. Expressionn : Actionn ; default : } Actionn+1 ; 68

Testing for vowel-ness switch (ch) { case 'a': case 'A': case 'e': case 'E':

Testing for vowel-ness switch (ch) { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U': System. out. println("vowel“); break; The break causes an exiting of the switch default: System. out. println("not a vowel“); } Handles all of the other cases 69

A better way to format that switch statement switch (ch) { case 'a': //

A better way to format that switch statement switch (ch) { case 'a': // FALL case 'A': // FALL case 'e': // FALL case 'E': // FALL case 'i': // FALL case 'I': // FALL. . . THRU THRU 70

Processing a request System. out. print("Enter a number: "); int n 1 = stdin.

Processing a request System. out. print("Enter a number: "); int n 1 = stdin. next. Int(); System. out. print("Enter another number: "); int n 2 = stdin. next. Int(); System. out. print("Enter desired operator: "); char operator = stdin. next. Line(). char. At(0); switch (operator) { case '+' : System. out. println(n 1 + n 2); break; case '-' : System. out. println(n 1 - n 2); break; case '*' : System. out. println(n 1 * n 2); break; case '/' : System. out. println(n 1 / n 2); break; default: System. out. println(“Illegal request“); } 71

Quick survey n a) b) c) d) I understand the switch statement… Very well

Quick survey n a) b) c) d) I understand the switch statement… Very well With some review, I’ll be good Not really Not at all 72

Biggest software errors n Ariane 5 rocket explosion (1996) n Pentium division error (1994)

Biggest software errors n Ariane 5 rocket explosion (1996) n Pentium division error (1994) n Patriot-Scud missile error (1991) n Mars Climate Orbiter (1999) n AT&T long distance (1990) n Therac-25, X-ray (1975 -1987) n NE US power blackout (2003) n References: http: //www 5. in. tum. de/~huckle/bugse. html, http: //en. wikipedia. org/wiki/Computer_bug, http: //www. cs. tau. ac. il/~nachumd/verify/horror. html – Due to loss of precision converting 64 -bit double to 16 -bit int – Due to incomplete look-up table (like an array) – Rounding error on the time – The missile did not intercept an incoming Scud missile, leaving 28 dead and 98 wounded – Onboard used metric units; ground computer used English units – Wrong break statement in C code – Badly designed software led to radiation overdose in chemotherapy patients – Flaw in GE software contributed to it 73

Testing objects for equality o Consider System. out. print("Enter an integer number: "); int

Testing objects for equality o Consider System. out. print("Enter an integer number: "); int n 1 = stdin. next. Int(); System. out. print("Enter another integer number: "); int n 2 = stdin. next. Int(); if (n 1 == n 2) { System. out. println("Same"); } else { System. out. println(“Different"); } What is the output if the user enters 88 both times? What is the output if the user enters 88 and 3? 75

Testing objects for equality o Consider String s 1 = “pastel”; String s 2

Testing objects for equality o Consider String s 1 = “pastel”; String s 2 = s 1; if (s 1 == s 2) { System. out. println("Same"); } else { System. out. println("Different"); } 76

Testing objects for equality o Memory looks like s 1 "pastel" s 2 o

Testing objects for equality o Memory looks like s 1 "pastel" s 2 o o The comparison is between the references! Thus, s 1 and s 2 are the same (they refer to the same object) 77

Testing objects for equality o Consider System. out. print("Enter a string: "); String s

Testing objects for equality o Consider System. out. print("Enter a string: "); String s 1 = stdin. next. Line(); System. out. print("Enter another string: "); String s 2 = stdin. next. Line(); if (s 1 == s 2) { System. out. println("Same"); } else { System. out. println("Different"); } What is the output if the user enters "pastel" both times? 78

Testing objects for equality o o o When it is executed System. out. print("Enter

Testing objects for equality o o o When it is executed System. out. print("Enter a string: "); String s 1 = stdin. next. Line(); System. out. print("Enter another string: "); String s 2 = stdin. next. Line(); Memory looks like As a result no matter what is entered s 1 and s 2 are not the same 79 n They refer to different objects

Comparing strings for equality o o Consider: String s = "hello"; String t =

Comparing strings for equality o o Consider: String s = "hello"; String t = "hello"; System. out. println (s == t); What gets printed? n true Consider: String u = new String("hello"); String v = new String("hello"); System. out. println (u == v); What gets printed? n false n Huh? These aren’t the exact same thing 80

Testing operators for equality o Consider System. out. print("Enter a string: "); String s

Testing operators for equality o Consider System. out. print("Enter a string: "); String s 1 = stdin. next. Line(); System. out. print("Enter another string: "); String s 2 = stdin. next. Line(); Tests whether s 1 and s 2 represent the same object if (s 1. equals(s 2)) { System. out. println("Same"); } else { System. out. println("Different"); } All classes have a method equals(). Their implementation is class-specific. The String equals() method – like many 81 others – tests for equivalence in representation

Assignment vs. comparison o o = is the assignment operator n It copies the

Assignment vs. comparison o o = is the assignment operator n It copies the value on the right to the location on the left n Consider: int x; x = 5; n The value 5 is copied to the spot x in memory == is the comparison operator n Returns a boolean (true or false) if the two sides are equal n Consider: int x = 5; System. out. println (x == 5); System. out. println (x == 6); 82 n Prints out true, false

Some handy Character class methods o o is. Digit() n Tests whether character is

Some handy Character class methods o o is. Digit() n Tests whether character is numeric is. Letter() n Tests whether character is alphabetic is. Lower. Case() n Tests whether character is lowercase alphabetic is. White. Space() n Tests whether character is one of the space, tab, formfeed, or newline characters 83

Some handy Character class methods o o o is. Upper. Case() n Tests whether

Some handy Character class methods o o o is. Upper. Case() n Tests whether character is uppercase alphabetic to. Lower. Case() n If the character is alphabetic then the lowercase equivalent of the character is returned; otherwise, the character is returned to. Upper. Case() n If the character is alphabetic then the uppercase equivalent of the character is returned; otherwise, the character is returned 84

Quick survey n a) b) c) d) I understand comparing Strings and assignment vs.

Quick survey n a) b) c) d) I understand comparing Strings and assignment vs. comparison… Very well With some review, I’ll be good Not really Not at all 85

Why speling is not so important… I cdnuolt blveieetaht I cluod aulaclty uesdnatnrd waht

Why speling is not so important… I cdnuolt blveieetaht I cluod aulaclty uesdnatnrd waht I was rdanieg. The phaonmneal pweor of thehmuan mind. Aoccdrnig to a rscheearch at Cmabrigde Uinervtisy, it deosn't mttaer in waht oredr the ltteers in a wrod are, the olny iprmoatnt tihng is taht thefrist and lsat ltteer be in the rghit pclae. The rset can be a taotl mses andyou can sitll raed it wouthit a porbelm. Tihs is bcuseae the huamn mnid deosnot raed ervey lteter by istlef, but the wrod as a wlohe. Amzanig huh? yaeh and I awlyas thought slpeling was ipmorantt. 86

Short-circuit evaluation o o The value of a logical expression can be known before

Short-circuit evaluation o o The value of a logical expression can be known before all the operands have been considered n If left operand of && is false, then the value must be false n If right operand of || is true, then the value must be true Java uses these properties to make logical operations efficient n Evaluates left operand before it evaluates right operand n If the operator value is determined from the left operand, then the right operand is not evaluated o The operation is short-circuited 87

Short-circuit evaluation o o o Short-circuit evaluation is useful when some property must be

Short-circuit evaluation o o o Short-circuit evaluation is useful when some property must be true for some other expression to be evaluated Suppose you are interested in knowing whether score. Sum divided by nbr. Scores is greater than value n The condition can be evaluated only if nbr. Scores is nonzero The following expression correctly represents the condition (nbr. Scores != 0) && ((score. Sum / nbr. Scores) > value) 88

class Short. Circuit { static boolean returns. False() { System. out. println ("returns. False()

class Short. Circuit { static boolean returns. False() { System. out. println ("returns. False() called"); return false; } static boolean returns. True() { System. out. println ("returns. True() called"); return true; } Output public static void main (String args[]) { if ( returns. False() && returns. True() ) { } if ( returns. True() && returns. False() ) { } } } returns. False() called returns. True() called returns. False() called if ( returns. False() || returns. True() ) { } returns. False() called returns. True() called if ( returns. True() || returns. False() ) { } returns. True() called 89

A digression: Perl o Perl uses short-circuit evaluation also: n o o open (LOGFILE,

A digression: Perl o Perl uses short-circuit evaluation also: n o o open (LOGFILE, ">outputfile") || die (“Cannot open outputfile!); If the open command succeeds, then the die command is not evaluated If the open command fails, then the die command is evaluated 90

Quick survey n a) b) c) d) I understand short circuit evaluation… Very well

Quick survey n a) b) c) d) I understand short circuit evaluation… Very well With some review, I’ll be good Not really Not at all 91

All your base are belong to us 92

All your base are belong to us 92

A Circle class o o We are going to develop a Circle class n

A Circle class o o We are going to develop a Circle class n Perhaps for use in a graphics program Why? n Partly to review creating classes n Go over some topics that were a bit fuzzy o Constructors and creating objects n Show why one uses the get/set methods instead of directly modifying the instance variables 93

Circle class properties o o What properties does a circle have? n Radius n

Circle class properties o o What properties does a circle have? n Radius n PI = 3. 141592653589793234 n Color (if plotting in a graphics program) n (x, y) location These properties will become instance variables n We are only going to play with the first two (radius and PI) in this example n Thus, we are ignoring the color and location 94

Our Circle class Note the radius field is not initialized by us public class

Our Circle class Note the radius field is not initialized by us public class Circle { double radius; double PI = 3. 1415926536; } c Circle - radius = 0. 0 - PI = 3. 14159… -… We’re ignoring the public for now Note the fields are not static +… 95

Accessing our Circle object o Any variable or method in an object can be

Accessing our Circle object o Any variable or method in an object can be accessed by using a period n The period means ‘follow the reference’ n n n Example: System. in c Example: System. out. println (c. radius); Example: c. PI = 4; This is bad – PI should have been declared final (this will be done later) Circle - radius = 0. 0 - PI = 3. 14159… -… +… 96

What’s the output? public class Circle { double radius; double PI = 3. 1415926536;

What’s the output? public class Circle { double radius; double PI = 3. 1415926536; } public class Circle. Test { public static void main (String[] args) { int x; Circle c = new Circle(); System. out. println (x); Java will give a } “variable not } initialized” error o When a variable is declared as part of a method, Java does not initialize it to a default value 97

What’s the output now? public class Circle { double radius; double PI = 3.

What’s the output now? public class Circle { double radius; double PI = 3. 1415926536; } public class Circle. Test { public static void main (String[] args) { int x; Circle c = new Circle(); System. out. println (c. radius); Java } } o outputs 0. 0! When a variable is declared as part of a class, Java does initialize it to a default value 98

What’s going on? o A (method) variable needs to be initialized before it is

What’s going on? o A (method) variable needs to be initialized before it is used n o A instance variable is automatically initialized by Java n o Usually called a local variable All numbers are initialized to 0, booleans to false, etc. This is a bit counter-intuitive… 99

Circle class behaviors o o What do we want to do with (and to)

Circle class behaviors o o What do we want to do with (and to) our Circle class? n Create circles n Modify circles (mutators) n Find out about our circles’ properties (accessors) n Find the area of the circle n Plot it on the screen (or printer) n A few others… These will be implemented as methods 100

Calling the Circle constructor o To create a Circle object: c 1 Circle c

Calling the Circle constructor o To create a Circle object: c 1 Circle c 1 = new Circle(); o o This does four things: n Creates the c 1 reference n Creates the Circle object n Makes the c 1 reference point to the Circle object n Calls the constructor with no parameters (the ‘default’ constructor) Circle - radius = 0. 0 - PI = 3. 14159… -… + Circle() + Circle (double r) +… The constructor is always the first method called when creating (or ‘constructing’) an object 101

Calling the Circle constructor o To create a Circle object: c 1 Circle c

Calling the Circle constructor o To create a Circle object: c 1 Circle c 1 = new Circle(2. 0); o o This does four things: n Creates the c 1 reference n Creates the Circle object n Makes the c 1 reference point to the Circle object n Calls the constructor with 1 double parameters (the ‘specific’ constructor) Circle - radius = 0. 0 - PI = 3. 14159… -… + Circle() + Circle (double r) +… The constructor is always the first method called when creating (or ‘constructing’) an object 102

Constructors o Remember, the purpose of the constructor is to initialize the instance variables

Constructors o Remember, the purpose of the constructor is to initialize the instance variables n PI is already set, so only radius needs setting public Circle() { radius = 1. 0; } public Circle (double r) { radius = r; } Note there is no return type for constructors Note that the constructor name is the EXACT same as the class name Note that there are two “methods” with the same name! 103

Quick survey n a) b) c) d) How are we doing with constructors? I

Quick survey n a) b) c) d) How are we doing with constructors? I totally got it It’s making a lot more sense now I’m still a bit confused I have no idea what you were talking about 104

Demotivators 105

Demotivators 105

What happens in memory o o o Consider: Circle c = new Circle(); A

What happens in memory o o o Consider: Circle c = new Circle(); A double takes up 8 bytes in memory Thus, a Circle object takes up 16 bytes of memory n As it contains two doubles Circle c - radius = 1. 0 - PI = 3. 1415926536 -… + Circle() + Circle (double r) +… Shorthand representation c Circle - radius = 1. 0 - PI = 3. 14159 106

Consider the following code public class Circle. Test { public static void main (String[]

Consider the following code public class Circle. Test { public static void main (String[] args) { Circle c 1 = new Circle(); Circle c 2 = new Circle(); Circle c 3 = new Circle(); Circle c 4 = new Circle(); } } 107

What happens in memory There are 4 Circle objects in memory n Taking up

What happens in memory There are 4 Circle objects in memory n Taking up a total of 4*16 = 64 bytes of memory o c 1 Circle - radius = 1. 0 - PI = 3. 14159 c 2 Circle - radius = 1. 0 - PI = 3. 14159 c 3 Circle - radius = 1. 0 - PI = 3. 14159 c 4 Circle - radius = 1. 0 - PI = 3. 14159 108

Consider the following code public class Circle. Test { public static void main (String[]

Consider the following code public class Circle. Test { public static void main (String[] args) { Circle c 1 = new Circle(); //. . . Circle c 1000000 = new Circle(); } } This program creates 1 million Circle objects! 109

What happens in memory o There are 1 million Circle objects in memory n

What happens in memory o There are 1 million Circle objects in memory n Taking up a total of 1, 000*16 ≈ 16 Mb of memory c 1 c 2 Circle - radius = 1. 0 - PI = 3. 14159 c 1000000 … Circle - radius = 1. 0 - PI = 3. 14159 Note that the final PI field is repeated 1 million times 110

The use of static for fields o If a variable is static, then there

The use of static for fields o If a variable is static, then there is only ONE of that variable for ALL the objects n That variable is shared by all the objects 16 (1+1=2 doubles) Total memory Total usage: memory 8 Mb usage: + 8 40 bytes (1, 000+1=1, 000, 001 (4+1=5 doubles) c 1 c 2 c 3 Circle - radius = 1. 0 PI … c 1000000 c 4 Circle - radius = 1. 0 3. 1415926536 111

More on static fields o What does the following print n Note that PI

More on static fields o What does the following print n Note that PI is not final Circle c 1 = new Circle(); Circle c 2 = new Circle(); Circle c 3 = new Circle(); Circle c 4 = new Circle(); c 1. PI = 4. 3; System. out. println (c 2. PI); o Note you can refer to static fields by object. variable It prints 4. 3 112

Even more on static fields o o o There is only one copy of

Even more on static fields o o o There is only one copy of a static field no matter how many objects are declared in memory n Even if there are zero objects declared! n The one field is “common” to all the objects Static variables are called class variables n As there is one such variable for all the objects of the class n Whereas non-static variables are called instance variables Thus, you can refer to a static field by using the class name: n Circle. PI 113

Even even more on static fields o This program also prints 4. 3: Circle

Even even more on static fields o This program also prints 4. 3: Circle c 1 = new Circle(); Circle c 2 = new Circle(); Circle c 3 = new Circle(); Circle c 4 = new Circle(); Circle. PI = 4. 3; System. out. println (c 2. PI); 114

Even even more on static fields o We’ve seen static fields used with their

Even even more on static fields o We’ve seen static fields used with their class names: n System. in (type: Input. Stream) n System. out (type: Output. Stream) n Math. PI (type: double) n Integer. MAX_VALUE (type: int) 115

Quick survey n a) b) c) d) How are we doing with static fields?

Quick survey n a) b) c) d) How are we doing with static fields? I totally got it More or less I’m still a bit confused I have no idea what you were talking about 116

How much will Christmas cost? 117

How much will Christmas cost? 117

Back to our Circle class public class Circle { double radius; final static double

Back to our Circle class public class Circle { double radius; final static double PI = 3. 1415926536; public Circle() { radius = 1. 0; } Note that PI is now final and static public Circle (double r) { radius = r; } } o But it doesn’t do much! 118

Adding a method public class Circle { double radius; final static double PI =

Adding a method public class Circle { double radius; final static double PI = 3. 1415926536; // Constructors. . . double compute. Area () { return PI*radius; } } Note that a (non-static) method can use both instance and class variables 119

Using that method public class Circle. Test { public static void main (String[] args)

Using that method public class Circle. Test { public static void main (String[] args) { Circle c = new Circle(); c. radius = 2. 0; System. out. println (c. compute. Area()); } } Prints 12. 566370614356 120

Review of our Circle class public class Circle { double radius; final static double

Review of our Circle class public class Circle { double radius; final static double PI = 3. 1415926536; public Circle() { } Slight change from before public Circle (double r) { radius = r; } double compute. Area () { return PI*radius; } } 122

Adding another method double one. Over. Radius() { return 1. 0/radius; } o I

Adding another method double one. Over. Radius() { return 1. 0/radius; } o I couldn’t think of a good reason to divide something by the radius… 123

What happens now? o Code in class Circle. Test’s main() method Circle c =

What happens now? o Code in class Circle. Test’s main() method Circle c = new Circle(); // c. radius is now 0. 0 System. out. println (c. one. Over. Radius()); o o Java won’t crash, but many other programming languages (C and C++, in particular) will n So we’ll call this a ‘crash’ for the sake of this lecture Java prints “Infinity” n Not what we wanted, though! 124

One way to fix this… public class Circle { double radius = 1. 0;

One way to fix this… public class Circle { double radius = 1. 0; final static double PI = 3. 1415926536; Note that the radius variable is now initialized to 1. 0 // Constructors. . . double compute. Area () { return PI*radius; } double one. Over. Radius() { return 1. 0/radius; } } 125

Back to our program… o This code will now run properly: Circle c =

Back to our program… o This code will now run properly: Circle c = new Circle(); // c. radius = 1. 0 System. out. println (c. one. Over. Radius()); o But this code will “crash”: Circle c = new Circle(); // c. radius = 1. 0 c. radius = 0. 0; System. out. println (c. one. Over. Radius()); 126

Where the “crash” occurs public class Circle. Test { public static void main (String[]

Where the “crash” occurs public class Circle. Test { public static void main (String[] args) { public class Circle { double radius = 1. 0; final static double PI = 3. 1415926536; Circle c = new Circle(); // c. radius = 1. 0 c. radius = 0. 0; System. out. println (c. one. Over. Radius()); } } Here is the badly written code double compute. Area () { return PI*radius; } double one. Over. Radius() { return 1. 0/radius; } Here is where the “crash” occurs 127

Motivation for private fields o o o Problem: We do not want people using

Motivation for private fields o o o Problem: We do not want people using our Circle class to be able to modify the fields on their own Solution: Don’t allow other code to modify the radius field n Give it private visibility private means that only code within the class can modify the field 128

One way to fix this… public class Circle { private double radius = 1.

One way to fix this… public class Circle { private double radius = 1. 0; final static double PI = 3. 1415926536; Note that the radius variable is now private // Constructors. . . double compute. Area () { return PI*radius; } double one. Over. Radius() { return 1. 0/radius; } } 129

Back to our program… o This code will now not compile: Circle c =

Back to our program… o This code will now not compile: Circle c = new Circle(); // c. radius = 1. 0 c. radius = 0. 0; System. out. println (c. one. Over. Radius()); o Java will give a compile-time error: n radius has private access in Circle 130

Back to our program… o This code will also not compile: Circle c =

Back to our program… o This code will also not compile: Circle c = new Circle(); // c. radius = 1. 0 System. out. println (c. radius); o Java will give the same compile-time error: n radius has private access in Circle 131

The problem now… o But now you can’t have a Circle with a radius

The problem now… o But now you can’t have a Circle with a radius other than 1. 0! o Solution: Use a get/set methods in Circle: o A mutator method: void set. Radius (double r) { radius = r; } o An accessor method: double get. Radius () { return radius; } 132

Our Circle class so far public class Circle { private double radius = 1.

Our Circle class so far public class Circle { private double radius = 1. 0; final static double PI = 3. 1415926536; // Constructors. . . double compute. Area () { return PI*radius; } double one. Over. Radius() { return 1. 0/radius; } void set. Radius (double r) { radius = r; } double get. Radius () { return radius; } } 133

Using the get/set methods public class Circle. Test { public static void main (String[]

Using the get/set methods public class Circle. Test { public static void main (String[] args) { public class Circle { private double radius = 1. 0; final static double PI = 3. 1415926536; double compute. Area () { return PI*radius; } Circle c = new Circle(); c. set. Radius (1. 0); double one. Over. Radius() { return 1. 0/radius; } System. out. println (c. compute. Area()); void set. Radius (double r) { radius = r; } System. out. println (c. get. Radius()); } double get. Radius () { return radius; } } Here a method is invoked } 134 Here the change to radius occurs

Wait! Another problem! public class Circle. Test { public static void main (String[] args)

Wait! Another problem! public class Circle. Test { public static void main (String[] args) { Circle c = new Circle(); c. set. Radius (0. 0); Here is the problem now… System. out. println (c. one. Over. Radius()); } } 135

This problem is easily fixed o Change the set. Radius method to the following

This problem is easily fixed o Change the set. Radius method to the following void set. Radius (double r) { if ( r > 0. 0 ) radius = r; else radius = 1. 0; } o Now there is (almost) no way for code outside the Circle class to change the radius to zero 136

Visibilities in Java o There are four visibilities: n private: Only code within the

Visibilities in Java o There are four visibilities: n private: Only code within the same class can access the field or method o Note: “access” means reading or writing the field, or invoking the method n n n public: Any code, anywhere, can access the field or method protected: Used with inheritance o We won’t get to that this semester default: Almost the same as public o This is the default (duh!) o Note that it can’t be specified like the others 137

A few notes on visibilities o o You can NOT specify visibilities for method

A few notes on visibilities o o You can NOT specify visibilities for method variables n Any method variable can only be accessed within that method o Think of it as public within the method (after it’s defined) and private outside the method You can also specify visibilities for methods and classes n We won’t get to that in this course 138

Quick survey n a) b) c) d) I understand visibilities in Java… Very well

Quick survey n a) b) c) d) I understand visibilities in Java… Very well With some review, I’ll be good Not really Not at all 139

Today’s demotivators 140

Today’s demotivators 140

Overriding methods (and constructors) o Consider the following code: Circle c 1 = new

Overriding methods (and constructors) o Consider the following code: Circle c 1 = new Circle (); Circle c 2 = new Circle (2. 0); o o o Creates a Circle of radius 1. 0 Creates a Circle of radius 2. 0 Java knows which constructor to call by the list of parameters n This is called “overloading” n Meaning it means multiple things, depending on the context We’ve seen overloading before: n 3+4 Performs integer addition n 3. 0+4. 0 Performs floating-point addition n “ 3”+” 4” Performs string concatenation The ‘+’ operator is overloaded 141

Overriding methods (and constructors), take 2 o The following Circle constructors would not be

Overriding methods (and constructors), take 2 o The following Circle constructors would not be allowed: n We are assuming PI is not final for this example public Circle() { radius = 1. 0; } public Circle (double r) { radius = r; } When Circle(1. 0) is called, which one is meant? public Circle (double p) { PI = p; } 142

Using mutators in the constructor o Our second constructor has a problem: public Circle

Using mutators in the constructor o Our second constructor has a problem: public Circle (double r) { radius = r; } o Consider the following code: Circle c = new Circle (0. 0); System. out. println (c. one. Over. Radius()); The method is dividing by zero (again) 143

Using mutators in the constructor o This is easily fixed! o Our revised constructors:

Using mutators in the constructor o This is easily fixed! o Our revised constructors: public Circle() { set. Radius (1. 0); } public Circle (double r) { set. Radius (r); } o The mutator will properly set the radius (and won’t set it to zero) 144

Why we always use the mutators o Consider a modified version of our circle

Why we always use the mutators o Consider a modified version of our circle class: class Circle { double radius; double diameter; String size; //. . . o o Our mutator now looks like this: That’s a lot of code to copy if you decide not to call the mutator! void set. Radius (double r) { if ( radius <= 0. 0 ) radius = 1. 0; else radius = r; diameter = 2*radius; if ( radius < 1. 0 ) size = “small”; else if ( radius < 5. 0 ) size = “medium”; else if ( radius < 10. 0 ) size = “large”; else size = “huge”; } 145

Back to the static discussion o o Remember that there is one (and only

Back to the static discussion o o Remember that there is one (and only one) static PI field, regardless of how many objects are declared Consider the following method: double get. PI() { return PI; } o o It doesn’t read or modify the “state” of any object n In this example, it doesn’t read/write the radius In fact, that particular method doesn’t care anything about the objects declared n It’s only accessing a static field 147

Make get. PI() static o Consider the following: static double get. PI() { return

Make get. PI() static o Consider the following: static double get. PI() { return PI; } o o As the method is static, it can ONLY access static fields A static method does not care about the “state” of an object n Examples: Math. sin(), Math. tan(), Math. cos() o They don’t care about the state of any Math object o They only perform the computation 148

Invoking static methods o As with static fields, they can be called using either

Invoking static methods o As with static fields, they can be called using either an object or the class name: Circle c = new Circle(); System. out. println (c. get. PI()); System. out. println (Circle. get. PI()); o Static methods are also called class methods 149

static methods and non-static fields o Consider the following (illegal) Circle method: static double

static methods and non-static fields o Consider the following (illegal) Circle method: static double get. Radius() { return radius; } o And the code to invoke it: public static void main (String[] args) { Circle c 1 = new Circle(); Circle c 2 = new Circle(); Circle c 3 = new Circle(); Circle c 4 = new Circle(); System. out. println (Circle. get. Radius()); } 150

What happening in memory o There are no 4 million 1 Circleobjects Circle objects

What happening in memory o There are no 4 million 1 Circleobjects Circle objects ininmemory in memory o Which radius field does Circle. get. Radius() want? c 1 c 2 c 3 Circle - radius = 1. 0 PI … c 1000000 c 4 Circle - radius = 1. 0 3. 1415926536 151

The main static lesson o o A static method cannot access or modify the

The main static lesson o o A static method cannot access or modify the state of the object it is a part of If you remember nothing else about static methods, remember this! 152

static and non-static rules o o Non-static fields and methods can ONLY be accessed

static and non-static rules o o Non-static fields and methods can ONLY be accessed by the object name Static fields and methods can be accessed by EITHER the class name or the object name Non-static methods can refer to BOTH static and non-static fields Static methods can ONLY access static fields of the class they are part of 153

Back to our main() method public static void main (String[] args) We’ll learn about

Back to our main() method public static void main (String[] args) We’ll learn about arrays in chapter 8 The method does not return a value Any code anywhere can call this method It’s a static method: • Can’t access non-static fields or methods directly • Can be called only by the class name 154

Quick survey n a) b) c) d) I felt I understood the material in

Quick survey n a) b) c) d) I felt I understood the material in this slide set… Very well With some review, I’ll be good Not really Not at all 155

Quick survey n a) b) c) d) The pace of the lecture for this

Quick survey n a) b) c) d) The pace of the lecture for this slide set was… Fast About right A little slow Too slow 156

Quick survey n a) b) c) d) How interesting was the material in this

Quick survey n a) b) c) d) How interesting was the material in this slide set? Be honest! Wow! That was SOOOOOOO cool! Somewhat interesting Rather boring Zzzzzz 157

Sidewalk chalk guy n Source: http: //www. gprime. net/images/sidewalkchalkguy/ 158

Sidewalk chalk guy n Source: http: //www. gprime. net/images/sidewalkchalkguy/ 158