# Quiz About [Your topic] - University of Virginia School of ...

Decisions, decisions, decisions Chapter 5 Spring 2005 CS 101 Aaron Bloomfield 1 Background Our problem-solving solutions so far have the straight-line property They execute the same statements for every run of the program public class DisplayForecast // 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 For general problem solving we need more capabilities The ability to control which statements are executed 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 The if constructs use logical expressions to determine their course of action Examination begins with logical expressions 3 Logical expressions The branch of mathematics dealing with logical expressions is Boolean algebra Developed by the British mathematician George Boole 4 Logical expressions

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

There are three primary logical operators for manipulating logical values Logical and Logical or Logical not The operators work as most of us would expect 6 Quick survey a) b) c) d)

Ive seen Boolean logic before Lots and lots and lots A fair amount Some Not really 7 More demotivators 8 Truth tables We use truth tables to give formal specifications of the operators It works as most of us would expect allows for ambiguity of interpretation

Jim is smiling or Patty is smiling Can both Jim and Patty both be smiling? Truth tables Lists all combinations of operand values and the result of the operation for each combination p q p and q False False True True False True False True False False False

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

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

q p and q not (p and q) False False True True False True False True False False False True True

True True False 11 DeMorgans laws not (p and q) equals (not p) or (not q) p False False True True q False True False True

p and q False False False True not (p and q) ( not p) True True True False (not p) or (not q) (not q) True True True False

False True False False True True True False 12 DeMorgans laws not (p or q) equals (not p) and (not q) p False False True True q

False True False True p or q False False False True not (p or q) True False False False ( not p) (not p) and

(not q) (not q) True True True False False True False False True False False False 13 DeMorgans laws If you remember nothing else about the Boolean operators, remember that:

not (a and b) == (not a) or (not b) not (a or b) == (not a) and (not b) 14 A boolean type Java has the logical type boolean Type boolean has two literal constants true false

Operators The and operator is && Dont use & The or operator is || Dont use | The not operator is ! 15 Defining boolean variables Local boolean variables are uninitialized by default boolean isWhitespace; boolean receivedAcknowledgement; boolean haveFoundMissingLink; isWhitespace

- receivedAcknowledgement - haveFoundMissingLink - 16 Defining boolean variables Local boolean variables with initialization boolean canProceed = true; boolean preferCyan = false; boolean completedSecretMission = true; canProceed

true preferCyan false completedSecretMission true 17 Defining boolean variables Instance boolean variables are initialized to false by default boolean isWhitespace; boolean receivedAcknowledgement; boolean haveFoundMissingLink; isWhitespace false

receivedAcknowledgement false haveFoundMissingLink false 18 DeCSS: The program #include typedef unsigned int uint; char ctb[512]="33733b2663236b763e7e362b6e2e667bd393db0643034b96de9ed60b4e0e4\ 69b57175f82c787cf125a1a528fca8ac21fd999d10049094190d898d001480840913d7d35246\ d2d65743c7c34256c2c6475dd9dd5044d0d4594dc9cd4054c0c449559195180c989c11058185\ 081c888c011d797df0247074f92da9ad20f4a0a429f53135b86c383cb165e1e568bce8ec61bb\ 3f3bba6e3a3ebf6befeb6abeeaee6fb37773f2267276f723a7a322f6a2a627fb9f9b1a0e9a9e\ 1f0b8f8b0a1e8a8e0f15d1d5584cd8dc5145c1c5485cc8cc415bdfdb5a4edade5f4bcfcb4a5e\ cace4f539793120692961703878302168286071b7f7bfa2e7a7eff2bafab2afeaaae2ff"; typedef unsigned char uchar;uint tb0[11]={5,0,1,2,3,4,0,1,2,3,4};uchar* F=NULL; uint lf0,lf1,out;void ReadKey(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;lf0=(key[1]<<9)|

key[0]|0x100;lf1=(key[4]<<16)|(key\ [3]<<8)|key[2];lf1=((lf1&0xfffff8)<<1)|(lf1&0x7)| 0x8;}uchar Cipher(int sw1,\ int sw2){int i,a,b,x=0,y=0;for(i=0;i<8;i++) {a=((lf0>>2)^(lf0>>16))&1;b=((lf1\ >>12)^(lf1>>20)^(lf1>>21)^(lf1>>24))&1;lf0=(lf0<<1)|a;lf1=(lf1<<1)|b;x=(x>>1)\ | (a<<7);y=(y>>1)|(b<<7);}x^=sw1;y^=sw2;return out=(out>>8)+x+y;} void \ CSSdescramble(uchar *sec,uchar *key){uint i;uchar *end=sec+0x800;uchar KEY[5]; for(i=0;i<5;i++)KEY[i]=key[i]^sec[0x54+i];ReadKey(KEY);sec+=0x80;while(sec!=\ end)*sec+ +=F[*sec]^Cipher(255,0);}void CSStitlekey1(uchar *key,uchar *im) {uchar k[5];int i; ReadKey(im);for(i=0;i<5;i++)k[i]=Cipher(0,0);for(i=9;i>=0;\ i--)key[tb0[i+1]]=k[tb0[i+1]]^F[key[tb0[i+1]]]^key[tb0[i]];}void CSStitlekey2\ (uchar *key,uchar *im){uchar k[5];int i;ReadKey(im);for(i=0;i<5;i++)k[i]=\ Cipher(0,255);for(i=9;i>=0;i--)key[tb0[i+1]]=k[tb0[i+1]]^F[key[tb0[i+1]]]^key\ [tb0[i]];}void CSSdecrypttitlekey(uchar *tkey,uchar *dkey){int i;uchar im1[6]; uchar im2[6]={0x51,0x67,0x67,0xc5,0xe0,0x00};for(i=0;i<6;i++)im1[i]=dkey[i]; CSStitlekey1(im1,im2);CSStitlekey2(tkey,im1);} 19 DeCSS: The shirt (and tie!) 20 DeCSS: The poem

How to decrypt a DVD: in haiku form. (Thanks, Prof. D. S. T.) -----------------------(I abandon my exclusive rights to make or perform copies of 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 Table Zero is: Five, zero, one, two, three, four, oh, one, two, three, four. Table One is long:

two to the eighth power bytes. Ready? Here they are: 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 DeCSS: The number The worlds first illegal prime number: 48565078965739782930984189469428613770744208735135792401965207366869851 34010472374469687974399261175109737777010274475280490588313840375497099 87909653955227011712157025974666993240226834596619606034851742497735846 85188556745702571254749996482194184655710084119086259716947970799152004 86670997592359606132072597379799361886063169144735883002453369727818139

14797955513399949394882899846917836100182597890103160196183503434489568 70538452085380458424156548248893338047475871128339598968522325446084089 71119771276941207958624405471613210050064598201769617718094781136220027 23448272249323259547234688002927776497906148129840428345720146348968547 16908235473783566197218622496943162271666393905543024156473292485524899 12257394665486271404821171381243882177176029841255244647445055834628144 88335631902725319590439283873764073916891257924055015620889787163375999 10788708490815909754801928576845198859630532382349055809203299960323447 11407760198471635311617130785760848622363702835701049612595681846785965 33310077017991614674472549272833486916000647585917462781212690073518309 24153010630289329566584366200080047677896798438209079761985949364630938 05863367214696959750279687712057249966669805614533820741203159337703099 49152746918356593762102220068126798273445760938020304479122774980917955 93838712100058876668925844870047077255249706044465212713040432118261010 3591186476662963858495087448497373476861420880529443 22 DeCSS: The images 23 DeCSS: The recordings

All this info from http://www-2.cs.cmu.edu/~dst/DeCSS/Gall ery/ Or do a Google search for decss gallery 24 DeCSS: The movie 25 Other operators Equality operators == and != Operator ==

Returns true if the operands have the same value; otherwise, returns false This is not the assignment operator! Operator != Returns true if the operands have different values; otherwise, returns false The operators work with all types of values 26 Evaluating boolean expressions

Suppose boolean boolean boolean 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 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 What gets printed? class FloatTest { public static void main (String args[]) { double y = 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1; System.out.println (y); } } FloatTest.java There are 10 0.1s 29

Take care with floating-point values Consider double a = 1; double b = 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 double c = .9999999999999999; 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 Instead with the ordering operators for closeness 30 How to solve this Dont compare floating-point values if you can help it! 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 Java provides ordering operators for the primitive types Four ordering operators, <, >, <=, and >= 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

Suppose int i = 1; int j = 2; int k = 2; What is the value of i= k i >= k 33 Unicode values Character comparisons are based on their Unicode values

Characters 0, 1, 9 have expected order Character 0 has the encoding 48 Character 1 has the encoding 49, and so on. Upper case Latin letters A, B, Z have expected order 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 Character a has the encoding 97 Character b has the encoding 98, and so on.

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

>= e >= e 35 Operator precedence revisited Highest to lowest Parentheses Unary operators Multiplicative operators Additive operators Relational ordering Relational equality Logical and Logical or Assignment 36 Expressions vs. statements

A statement is a single command for Java to do, and always ends in a semi-colon (for now, at least) System.out.println (hello world); int x = 4; ++x; An expression returns a value, and does not have a semicolon 5 circle.getRadius() x Note the difference between the following:

++i is an expression ++i; is a statement 37 Quick survey a) b) c) d) I felt I understood expressions Very well With some review, Ill be good Not really Not at all 38

A bit of humor 39 Conditional constructs Provide Ability to control whether a statement list is executed Two constructs If statement if if-else if-else-if

Switch statement 41 Basic if statement Syntax if (Expression) Action If the Expression is true then execute Action 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? 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 value1 = stdin.nextInt();

System.out.print("Enter another integer number: "); int value2 = stdin.nextInt(); // rearrange numbers if necessary if (value2 < value1) { // values are not in sorted order int rememberValue1 = value1; value1 = value2; value2 = rememberValue1; } What happens if the user enters 11 and 28? What happens if the user enters 11 and 4? // display values System.out.println("The numbers in sorted order are " + value1 + " and then " + value2); 44

Are the numbers out of order If semantics Rearrange value1 and value2 to put their values in the proper order value2 < value1 true false int rememberValue1 = value1 value1 = value2 value2 = rememberValue1 The numbers were rearranged into the proper order The numbers were initially in order The numbers are in order

What an if statement executes An if statement executes the next block of code A block is either: A single statement without curly brackets: if (a == b) System.out.println (a==b!!!); 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 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 a) b) c) d)

I felt I understood the if statement Very well With some review, Ill be good Not really Not at all 48 Todays demotivators 49 The if-else statement Syntax if (Expression) Action1 else Action2

If Expression is execute Action1 execute Action2 Expression true then otherwise The actions are either a single statement or a list of statements within braces true false

Action1 Action2 50 Finding the maximum of two values System.out.print("Enter an integer number: "); int value1 = stdin.nextInt();System.out.print("Enter another integer number: "); int value2 = stdin.nextInt(); But is it initialized? int maximum; if (value1 < value2) { // is value2 larger? maximum = value2; // yes: value2 is larger } else { // (value1 >= value2) maximum = value1; // no: value2 is not larger }

System.out.println("The maximum of " + value1 + " and " + value2 + " is " + maximum); 51 Finding the maximum of two values Is value2 larger than value1 Yes, it is . So value2 is larger than value1. In this case, maximum is set to value2 value1 < value2 true maximum = value2 Either case, maximum is set correctly No, its not. So value1 is at least as large as value2. In this case, maximum is set to value1

false maximum = value1 52 Why we use whitespace What does the following do? System.out.print("Enter an integer number: "); int value1 = stdin.nextInt(); System.out.print("Enter another integer number: "); int value2 = stdin.nextInt(); if (value2 < value1) { int rememberValue1 = value1; value1 = value2; value2 = rememberValue1; } System.out.println("The numbers in sorted order are " + value1 + " and then " + value2);

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

} if (a == b) { //... } else { //... } if (a == b) { //... } else { //... } 54 Quick survey a) b)

c) d) I felt I understood the if-else statement Very well With some review, Ill be good Not really Not at all 55 If-then-else precedence if (number != 0) if (number > 0) System.out.println("positive"); Which if does this else else refer to? System.out.println("negative"); 56

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 Consider if (number == 0) { System.out.println("zero"); } else { if (number > 0) { We can change

the whitespace of the code These braces arent 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 a) b) c) d)

I understand if-else-if Very well With some review, Ill be good Not really Not at all 59 60 Review of HW J4 61 Sorting three values For sorting values n1, n2, and n3 there are six possible orderings

n1 n2 n3 n1 n3 n2 n2 n1 n3 n2 n3 n1 n3 n1 n2 n3 n2 n1 Suppose s1, s2, s3 are to be a sorted version of n1, n2, and n3 62 Sorting three values if ((n1 <= n2) && (n2 <= n3)) s1 = n1; s2 = n2;

s3 = } else if ((n1 <= n3) && (n3 <= s1 = n1; s2 = n3; s3 = } else if ((n2 <= n1) && (n1 <= s1 = n2; s2 = n1; s3 = } else if ((n2 <= n3) && (n3 <= s1 = n2; s2 = n3; s3 = } else if ((n3 <= n1) && (n1 <= s1 = n3; s2 = n1; s3 = } else { // n3 <= n2 <= n1

s1 = n3; s2 = n2; s3 = } { n3; // n1 <= n2 <= n3 n2)) { // n1 <= n3 <= n2 n2; n3)) { // n2 <= n1 <= n3 n3; n1)) { // n2 <= n3 <= n1 n1; n2)) { // n3 <= n1 <= n2 n2; n1; 63 Finding the minimum value

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

Can be difficult to read 65 Switch statement Software engineers often confronted with programming tasks where required action depends on the values of integer expressions The if-else-if construct can be used Separately compare the desired expression to a particular value If the expression and value are equal, then perform the appropriate action

Because such programming tasks occur frequently Java includes a switch statement 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 == 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 ( SwitchExpression ) case CaseExpression1 : Action1 ; case CaseExpression2 : Action2 ; Java statements { Constant integral expression ... case CaseExpressionn : Actionn ; } default : Actionn+1 ;

68 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': // FALL

case 'A': // FALL case 'e': // FALL case 'E': // FALL case 'i': // FALL case 'I': // FALL ... THRU THRU THRU THRU THRU THRU 70 Processing a request System.out.print("Enter a number: "); int n1 = stdin.nextInt();

System.out.print("Enter another number: "); int n2 = stdin.nextInt(); System.out.print("Enter desired operator: "); char operator = stdin.nextLine().charAt(0); switch (operator) { case '+' : System.out.println(n1 + n2); break; case '-' : System.out.println(n1 - n2); break; case '*' : System.out.println(n1 * n2); break; case '/' : System.out.println(n1 / n2); break; default: System.out.println(Illegal request); } 71 Quick survey a) b) c) d) I understand the switch statement Very well

With some review, Ill be good Not really Not at all 72 Biggest software errors Ariane 5 rocket explosion (1996) Due to loss of precision converting 64-bit double to 16-bit int Pentium division error (1994) Due to incomplete look-up table (like an array) Patriot-Scud missile error (1991)

Rounding error on the time The missile did not intercept an incoming Scud missile, leaving 28 dead and 98 wounded Mars Climate Orbiter (1999) Onboard used metric units; ground computer used English units AT&T long distance (1990) Wrong break statement in C code Therac-25, X-ray (1975-1987) Badly designed software led to radiation overdose in chemotherapy patients

NE US power blackout (2003) Flaw in GE software contributed to it References: http://www5.in.tum.de/~huckle/bugse.html, http://en.wikipedia.org/wiki/Computer_bug, http:// www.cs.tau.ac.il/~nachumd/verify/horror.html 73 Testing objects for equality Consider System.out.print("Enter an integer number: "); int n1 = stdin.nextInt(); System.out.print("Enter another integer number: "); int n2 = stdin.nextInt(); if (n1 == n2) { 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 Consider String s1 = pastel; String s2 = s1; if (s1 == s2) { System.out.println("Same"); } else { System.out.println("Different"); } 76

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

Consider System.out.print("Enter a string: "); String s1 = stdin.nextLine(); System.out.print("Enter another string: "); String s2 = stdin.nextLine(); if (s1 == s2) { 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 When it is executed System.out.print("Enter a string: ");

String s1 = stdin.nextLine(); System.out.print("Enter another string: "); String s2 = stdin.nextLine(); Memory looks like s1 "pastel" s2 "pastel" As a result no matter what is entered s1 and s2 are not the same 79 They refer to different objects

Comparing strings for equality Consider: String s = "hello"; String t = "hello"; System.out.println (s == t); What gets printed? true Consider: String u = new String("hello"); String v = new String("hello"); System.out.println (u == v); What gets printed?

false Huh? These arent the exact same thing 80 Testing operators for equality Consider System.out.print("Enter a string: "); String s1 = stdin.nextLine(); System.out.print("Enter another string: "); String s2 = stdin.nextLine(); Tests whether s1 and s2 represent the same object if (s1.equals(s2)) { 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 = is the assignment operator It copies the value on the right to the location on the left Consider: int x; x = 5; The value 5 is copied to the spot x in memory

== is the comparison operator Returns a boolean (true or false) if the two sides are equal Consider: int x = 5; System.out.println (x == 5); System.out.println (x == 6); 82 Prints out true, false Some handy Character class methods isDigit() Tests whether character is numeric

isLetter() Tests whether character is alphabetic isLowerCase() Tests whether character is lowercase alphabetic isWhiteSpace() Tests whether character is one of the space, tab, formfeed, or newline characters 83 Some handy Character class methods isUpperCase()

Tests whether character is uppercase alphabetic toLowerCase() If the character is alphabetic then the lowercase equivalent of the character is returned; otherwise, the character is returned toUpperCase() If the character is alphabetic then the uppercase equivalent of the character is returned; otherwise, the character is returned 84 Quick survey

a) b) c) d) I understand comparing Strings and assignment vs. comparison Very well With some review, Ill be good Not really Not at all 85 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 The value of a logical expression can be known before all the operands have been considered If left operand of && is false, then the value must be false If right operand of || is true, then the value must be true Java uses these properties to make logical operations efficient Evaluates left operand before it evaluates right operand

If the operator value is determined from the left operand, then the right operand is not evaluated The operation is short-circuited 87 Short-circuit evaluation 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 scoreSum divided by nbrScores is greater than value The condition can be evaluated only if nbrScores is nonzero

The following expression correctly represents the condition (nbrScores != 0) && ((scoreSum / nbrScores) > value) 88 class ShortCircuit { static boolean returnsFalse() { System.out.println ("returnsFalse() called"); return false; } static boolean returnsTrue() { System.out.println ("returnsTrue() called"); return true; } Output public static void main (String args[]) { } }

if ( returnsFalse() && returnsTrue() ) { } returnsFalse() called if ( returnsTrue() && returnsFalse() ) { } returnsTrue() called returnsFalse() called if ( returnsFalse() || returnsTrue() ) { } returnsFalse() called returnsTrue() called if ( returnsTrue() || returnsFalse() ) { } returnsTrue() called A digression: Perl

Perl uses short-circuit evaluation also: 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

a) b) c) d) I understand short circuit evaluation Very well With some review, Ill be good Not really Not at all 91 All your base are belong to us Flash animation Reference: http://en.wikipedia.org/wiki/All_your_base_are_belong_to_us

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

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

94 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 - Were ignoring the public for now Note the fields

are not static + 95 Accessing our Circle object Any variable or method in an object can be accessed by using a period The period means follow the reference Example: System.in Example: System.out.println (c.radius);

Example: c.PI = 4; This is bad PI should have been declared final (this will be done later) c Circle - radius = 0.0 - PI = 3.14159 - + 96 Whats the output? public class Circle { double radius; double PI = 3.1415926536; } public class CircleTest {

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

Circle c = new Circle(); System.out.println (c.radius); Java } } outputs 0.0! When a variable is declared as part of a class, Java does initialize it to a default value 98 Whats going on? A (method) variable needs to be initialized before it is used A instance variable is automatically initialized by Java

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 What do we want to do with (and to) our Circle class? Create circles Modify circles (mutators) Find out about our circles properties (accessors) Find the area of the circle

Plot it on the screen (or printer) A few others These will be implemented as methods 100 Calling the Circle constructor To create a Circle object: c1 Circle c1 = new Circle(); This does four things:

Creates the c1 reference Creates the Circle object Makes the c1 reference point to the Circle object 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 To create a Circle object: c1 Circle c1 = new Circle(2.0); This does four things: Creates the c1 reference Creates the Circle object Makes the c1 reference point to the Circle object

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 Remember, the purpose of the constructor is to initialize the instance variables

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 a) b)

c) d) How are we doing with constructors? I totally got it Its making a lot more sense now Im still a bit confused I have no idea what you were talking about 104 Demotivators 105 What happens in memory Consider: Circle c = new Circle(); A double takes up 8 bytes in memory

Thus, a Circle object takes up 16 bytes of memory 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 CircleTest { public static void main (String[] args) { Circle c1 = new Circle(); Circle c2 = new Circle(); Circle c3 = new Circle(); Circle c4 = new Circle(); } } 107 What happens in memory There are 4 Circle objects in memory Taking up a total of 4*16 = 64 bytes of memory c1 Circle - radius = 1.0

- PI = 3.14159 c2 Circle - radius = 1.0 - PI = 3.14159 c3 Circle - radius = 1.0 - PI = 3.14159 c4 Circle - radius = 1.0 - PI = 3.14159 108 Consider the following code public class CircleTest {

public static void main (String[] args) { Circle c1 = new Circle(); //... Circle c1000000 = new Circle(); } } This program creates 1 million Circle objects! 109 What happens in memory There are 1 million Circle objects in memory Taking up a total of 1,000,000*16 16 Mb of memory c1 c2 Circle

- radius = 1.0 - PI = 3.14159 Circle - radius = 1.0 - PI = 3.14159 c1000000 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 If a variable is static, then there is only ONE of that variable for ALL the objects

That variable is shared by all the objects 16 (1+1=2 doubles) Total memory Total usage: memory 8 Mb usage: + 8 40 bytes bytes (1,000,000+1=1,000,001 (4+1=5 doubles) c1 Circle - radius = 1.0 c2 c3

Circle - radius = 1.0 PI Circle - radius = 1.0 3.14159265 36 c1000000 c4 Circle - radius = 1.0 111 More on static fields

What does the following print Note that PI is not final Circle c1 = new Circle(); Circle c2 = new Circle(); Circle c3 = new Circle(); Circle c4 = new Circle(); c1.PI = 4.3; System.out.println (c2.PI); Note you can refer to static fields by object.variable It prints 4.3 112 Even more on static fields

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

Circle.PI 113 Even even more on static fields This program also prints 4.3: Circle c1 = new Circle(); Circle c2 = new Circle(); Circle c3 = new Circle(); Circle c4 = new Circle(); Circle.PI = 4.3; System.out.println (c2.PI); 114 Even even even more on static fields Weve seen static fields used with their class names: System.in

(type: InputStream) System.out (type: OutputStream) Math.PI (type: double) Integer.MAX_VALUE (type: int) 115 Quick survey a) b) c) d) How are we doing with static fields? I totally got it More or less

Im still a bit confused I have no idea what you were talking about 116 How much will Christmas cost? http://www.pncbank.com/12days Flash animation (local) 117 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; } } But it doesnt do much! 118 Adding a method public class Circle { double radius; final static double PI = 3.1415926536; // Constructors... double computeArea () { return PI*radius*radius; } } Note that a (non-static) method can use both instance and class

variables 119 Using that method public class CircleTest { public static void main (String[] args) { Circle c = new Circle(); c.radius = 2.0; System.out.println (c.computeArea()); } } Prints 12.566370614356 120 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 computeArea () { return PI*radius*radius; } } 122 Adding another method double oneOverRadius() { return 1.0/radius; } I couldnt think of a good reason to divide something by the radius 123 What happens now?

Code in class CircleTests main() method Circle c = new Circle(); // c.radius is now 0.0 System.out.println (c.oneOverRadius()); Java wont crash, but many other programming languages (C and C++, in particular) will So well call this a crash for the sake of this lecture Java prints Infinity Not what we wanted, though! 124 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 computeArea () { return PI*radius*radius; } double oneOverRadius() { return 1.0/radius; } } 125 Back to our program This code will now run properly: Circle c = new Circle(); // c.radius = 1.0 System.out.println (c.oneOverRadius());

But this code will crash: Circle c = new Circle(); // c.radius = 1.0 c.radius = 0.0; System.out.println (c.oneOverRadius()); 126 Where the crash occurs public class CircleTest { public static void main (String[] args) { public class Circle { double radius = 1.0; final static double PI = 3.1415926536; Circle c = new Circle(); double computeArea () { return PI*radius*radius;

// c.radius = 1.0 c.radius = 0.0; System.out.println (c.oneOverRadius()); } } Here is the badly written code } double oneOverRadius() { return 1.0/radius; } Here is where the crash occurs 127 Motivation for private fields Problem: We do not want people using our Circle class to be able to modify the fields on their own

Solution: Dont allow other code to modify the radius field 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.0; final static double PI = 3.1415926536; Note that the radius variable is now private // Constructors...

double computeArea () { return PI*radius*radius; } double oneOverRadius() { return 1.0/radius; } } 129 Back to our program This code will now not compile: Circle c = new Circle(); // c.radius = 1.0 c.radius = 0.0; System.out.println (c.oneOverRadius()); Java will give a compile-time error: radius has private access in Circle

130 Back to our program This code will also not compile: Circle c = new Circle(); // c.radius = 1.0 System.out.println (c.radius); Java will give the same compile-time error: radius has private access in Circle 131 The problem now But now you cant have a Circle with a radius other than 1.0!

Solution: Use a get/set methods in Circle: A mutator method: void setRadius (double r) { radius = r; } An accessor method: double getRadius () { return radius; } 132 Our Circle class so far public class Circle { private double radius = 1.0; final static double PI = 3.1415926536;

// Constructors... double computeArea () { return PI*radius*radius; } double oneOverRadius() { return 1.0/radius; } void setRadius (double r) { radius = r; } double getRadius () { return radius; } } 133 Using the get/set methods public class CircleTest { public static void main (String[] args) { public class Circle {

private double radius = 1.0; final static double PI = 3.1415926536; double computeArea () { return PI*radius*radius; } Circle c = new Circle(); c.setRadius (1.0); double oneOverRadius() { return 1.0/radius; } System.out.println (c.computeArea()); void setRadius (double r) { radius = r; } System.out.println (c.getRadius());

double getRadius () { return radius; } } } Here a method is invoked } 134 Here the change to radius occurs Wait! Another problem! public class CircleTest { public static void main (String[] args) { Circle c = new Circle(); c.setRadius (0.0); Here is the problem now System.out.println (c.oneOverRadius());

} } 135 This problem is easily fixed Change the setRadius method to the following void setRadius (double r) { if ( r > 0.0 ) radius = r; else radius = 1.0; } Now there is (almost) no way for code outside the Circle class to change the radius to zero 136

Visibilities in Java There are four visibilities: private: Only code within the same class can access the field or method Note: access means reading or writing the field, or invoking the method public: Any code, anywhere, can access the field or method protected: Used with inheritance We wont get to that this semester default: Almost the same as public

This is the default (duh!) Note that it cant be specified like the others 137 A few notes on visibilities You can NOT specify visibilities for method variables Any method variable can only be accessed within that method Think of it as public within the method (after its defined) and private outside the method You can also specify visibilities for methods and classes We wont get to that in this course

138 Quick survey a) b) c) d) I understand visibilities in Java Very well With some review, Ill be good Not really Not at all 139 Todays demotivators 140 Overriding methods (and constructors)

Consider the following code: Circle c1 = new Circle (); Circle c2 = new Circle (2.0); 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 This is called overloading Meaning it means multiple things, depending on the context Weve seen overloading before: 3+4

Performs integer addition 3.0+4.0Performs floating-point addition 3+4 Performs string concatenation The + operator is overloaded 141 Overriding methods (and constructors), take 2 The following Circle constructors would not be allowed: 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 Our second constructor has a problem: public Circle (double r) { radius = r; }

Consider the following code: Circle c = new Circle (0.0); System.out.println (c.oneOverRadius()); The method is dividing by zero (again) 143 Using mutators in the constructor This is easily fixed! Our revised constructors: public Circle() { setRadius (1.0); } public Circle (double r) { setRadius (r); }

The mutator will properly set the radius (and wont set it to zero) 144 Why we always use the mutators Consider a modified version of our circle class: class Circle { double radius; double diameter; String size; // ... Our mutator now looks like this:

Thats a lot of code to copy if you decide not to call the mutator! void setRadius (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 Remember that there is one (and only one) static PI field, regardless of how many objects are declared Consider the following method: double getPI() { return PI; } It doesnt read or modify the state of any object In this example, it doesnt read/write the radius In fact, that particular method doesnt care anything about the objects declared

Its only accessing a static field 147 Make getPI() static Consider the following: static double getPI() { return PI; } As the method is static, it can ONLY access static fields A static method does not care about the state of an object Examples: Math.sin(), Math.tan(), Math.cos()

They dont care about the state of any Math object They only perform the computation 148 Invoking static methods As with static fields, they can be called using either an object or the class name: Circle c = new Circle(); System.out.println (c.getPI()); System.out.println (Circle.getPI()); Static methods are also called class methods 149 static methods and non-static fields

Consider the following (illegal) Circle method: static double getRadius() { return radius; } And the code to invoke it: public static void main (String[] args) { Circle c1 = new Circle(); Circle c2 = new Circle(); Circle c3 = new Circle(); Circle c4 = new Circle(); System.out.println (Circle.getRadius()); } 150 What happening in memory There are 1 4 nomillion

Circle Circleobjects Circle objects objects ininmemory memory in memory Which radius field does Circle.getRadius() want? c1 Circle - radius = 1.0 c2 c3 Circle

- radius = 1.0 PI Circle - radius = 1.0 3.14159265 36 c1000000 c4 Circle - radius = 1.0 151 The main static lesson

A static method cannot access or modify the state of the object it is a part of If you remember remember this! nothing else about static methods, 152 static and non-static rules

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) Well learn about arrays in chapter 8

The method does not return a value Any code anywhere can call this method Its a static method: Cant access non-static fields or methods directly Can be called only by the class name 154 Quick survey a) b) c) d) I felt I understood the material in this slide set Very well With some review, Ill be good Not really Not at all

155 Quick survey 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

a) b) c) d) How interesting was the material in this slide set? Be honest! Wow! That was SOOOOOOO cool! Somewhat interesting Rather boring Zzzzzzzzzzz 157 Sidewalk chalk guy Source: http://www.gprime.net/images/sidewalkchalkguy/ 158

## Recently Viewed Presentations

• How To Manage Anterior Traumatic Instability of the Shoulder ... The IGHL has been identified as the primary static constraint against anterior, posterior, and inferior translation in cadaveric specimens when the humerus is abducted beyond 45 degrees. With the arm...
• Happy New Year! Chinese New Year How do we celebrate the New Year in U.S? Foods we eat? Activities? How long does it last? Origins of Chinese New Year History Channel History of the Holidays: Chinese New Year Video Questions...
• Current situation Strong expression of policy interest Focusing on economics of culture and creative industries Existence of a corpus of statistical methods and definition On going systematic exploration and assessment of the existing data Framework for further actions Clarify the...
• Society Confucius said the basis of society is the family Government Confucius said that government should be based on the family Filial Piety Respect for your elders "By nature men are pretty much alike, it is learning and practice that...
• Anna Collin. Application Support Assistants: Tara Etherington. Emma Foster. ... Student Employee Of The Year 2014 Awards. Henrietta White. Hilda Kwafo-Akoto. ... Do Tran. Jess Duffy. Joanne Leachman. Kate Blackmore. Kayleigh Toyra. Laura Yonish.
• The presence of chyme in the small intestine triggers the conversion of prosecretin into secretin which is absorbed into the blood stream and carried to the pancreas.
• Macbeth is shown a line of kings with Banquo at the end/demands to know the meaning but the witches vanish. Lennox enters/tells Macbeth that Macduff has fled to England/Macbeth sends people to capture his castle and kill his wife and...
• Dangling modifiers are often caused by authors starting their sentences with -ing verbs. While it is not a rule that you can NEVER start a sentence this way, beware of dangling modifiers that may appear! Starting a sentence with an...