decisions, decisions, decisions

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

Upload: hillary-nixon

Post on 31-Dec-2015

44 views

Category:

Documents


0 download

DESCRIPTION

Decisions, decisions, decisions. Chapter 5 Spring 2005 CS 101 Aaron Bloomfield. 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 - PowerPoint PPT Presentation

TRANSCRIPT

  • Decisions, decisions, decisionsChapter 5Spring 2005CS 101Aaron Bloomfield

  • BackgroundOur problem-solving solutions so far have the straight-line propertyThey execute the same statements for every run of the program

    public class DisplayForecast // main(): application entry pointpublic 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.);}}

  • BackgroundFor general problem solving we need more capabilitiesThe ability to control which statements are executedThe 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 executedThe if constructs use logical expressions to determine their course of action

    Examination begins with logical expressions

  • Logical expressionsThe branch of mathematics dealing with logical expressions is Boolean algebraDeveloped by the British mathematician George Boole

  • Logical expressionsA logical expression has either the value logical true or logical false

    Some expressions whose values are logical trueThe year 2004 is a leap yearA meter equals 100 centimeters

    Some expressions whose values are logical falseA triangle has four sidesThe area of square is always equal to twice its perimeter

  • Logical expressionsThere are three primary logical operators for manipulating logical valuesLogical andLogical orLogical not

    The operators work as most of us would expect

  • Quick surveyIve seen Boolean logic beforeLots and lots and lotsA fair amountSomeNot really

  • More demotivators

  • Truth tablesWe use truth tables to give formal specifications of the operatorsIt works as most of us would expect allows for ambiguity of interpretationJim is smiling or Patty is smilingCan both Jim and Patty both be smiling? Truth tablesLists all combinations of operand values and the result of the operation for each combination

  • Or and not truth tables

  • Boolean algebraCan create complex logical expressions by combining simple logical expressions

    not (p and q)

  • DeMorgans lawsnot (p and q) equals (not p) or (not q)

  • DeMorgans lawsnot (p or q) equals (not p) and (not q)

  • DeMorgans lawsIf 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)

  • A boolean typeJava has the logical type boolean

    Type boolean has two literal constantstruefalse

    OperatorsThe and operator is &&Dont use &The or operator is ||Dont use |The not operator is !

  • Defining boolean variablesLocal boolean variables are uninitialized by default

    boolean isWhitespace;boolean receivedAcknowledgement;boolean haveFoundMissingLink;

  • Defining boolean variablesLocal boolean variables with initialization

    boolean canProceed = true;boolean preferCyan = false;boolean completedSecretMission = true;

  • Defining boolean variablesInstance boolean variables are initialized to false by default

    boolean isWhitespace;boolean receivedAcknowledgement;boolean haveFoundMissingLink;

  • 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;i21)^(lf1>>24))&1;lf0=(lf0
  • DeCSS: The shirt (and tie!)

  • DeCSS: The poemHow to decrypt aDVD: in haiku form.(Thanks, Prof. D. S. T.)------------------------

    (I abandon myexclusive rights to make orperform copies of

    this work, U. S. CodeTitle Seventeen, sectionOne Hundred and Six.)

    Muse! When we learned tocount, little did we know allthe things we could do

    some day by shufflingthose numbers: Pythagorassaid "All is number"

    long before he sawcomputers and their effects,or what they could doTable 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 onehundred fifteen; fifty nine;thirty eight; ninety

    nine; thirty five; onehundred seven; one hundredeighteen; sixty two;

    one hundred twentysix; fifty four; forty three;one hundred ten; then

  • DeCSS: The numberThe worlds first illegal prime number:

    485650789657397829309841894694286137707442087351357924019652073668698513401047237446968797439926117510973777701027447528049058831384037549709987909653955227011712157025974666993240226834596619606034851742497735846851885567457025712547499964821941846557100841190862597169479707991520048667099759235960613207259737979936188606316914473588300245336972781813914797955513399949394882899846917836100182597890103160196183503434489568705384520853804584241565482488933380474758711283395989685223254460840897111977127694120795862440547161321005006459820176961771809478113622002723448272249323259547234688002927776497906148129840428345720146348968547169082354737835661972186224969431622716663939055430241564732924855248991225739466548627140482117138124388217717602984125524464744505583462814488335631902725319590439283873764073916891257924055015620889787163375999107887084908159097548019285768451988596305323823490558092032999603234471140776019847163531161713078576084862236370283570104961259568184678596533310077017991614674472549272833486916000647585917462781212690073518309241530106302893295665843662000800476778967984382090797619859493646309380586336721469695975027968771205724996666980561453382074120315933770309949152746918356593762102220068126798273445760938020304479122774980917955938387121000588766689258448700470772552497060444652127130404321182610103591186476662963858495087448497373476861420880529443

  • DeCSS: The images

  • DeCSS: The recordingsAll this info from http://www-2.cs.cmu.edu/~dst/DeCSS/Gallery/

    Or do a Google search for decss gallery

  • DeCSS: The movie

  • Other operatorsEquality operators == and !=

    Operator ==Returns true if the operands have the same value; otherwise, returns falseThis 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

  • Evaluating boolean expressionsSupposeboolean p = true;boolean q = false;boolean r = true;boolean s = false;

    What is the value ofp p && s !s p == q q q != r p && r r == s q || s q != s

  • Evaluating boolean expressionsSupposeint i = 1;int j = 2;int k = 2;char c = '#';char d = '%';char e = '#';

    What is the value ofj == k i != ki == j j != kc == e d != ec == d c != e

  • Floating point precissionWhat 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.javaThere are 10 0.1s

  • Take care with floating-point valuesConsiderdouble a = 1;double b = 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1double c = .9999999999999999;

    Two true expressions! c == bb != a

    Two false expressions!a == bb != c

    Problem lies with the finite precision of the floating-point typesInstead with the ordering operators for closeness

  • How to solve thisDont 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;

  • Ordering operatorsJava provides ordering operators for the primitive typesFour ordering operators, , =They correspond to mathematical operators of , , and

    Together the equality and ordering operators are known as the relational operators

    False is less than true

  • Evaluation boolean expressionsSupposeint i = 1;int j = 2;int k = 2;

    What is the value ofi < jj < ki = ki >= k

  • Unicode valuesCharacter comparisons are based on their Unicode values

    Characters 0, 1, 9 have expected orderCharacter 0 has the encoding 48Character 1 has the encoding 49, and so on.

    Upper case Latin letters A, B, Z have expected orderCharacter A has the encoding 65, character B has the encoding 66, and so on.

    Lower case Latin letters a, b, z have expected orderCharacter a has the encoding 97Character b has the encoding 98, and so on.

  • Evaluation boolean expressionsSupposechar c = '2';char d = '3';char e = '2';

    What is the value ofc < dc < ec = ec >= e

  • Operator precedence revisitedHighest to lowestParenthesesUnary operatorsMultiplicative operatorsAdditive operatorsRelational orderingRelational equalityLogical andLogical orAssignment

  • Expressions vs. statementsA 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 semi-colon5circle.getRadius()x

    Note the difference between the following:++iis an expression++i;is a statement

  • Quick surveyI felt I understood expressionsVery wellWith some review, Ill be goodNot reallyNot at all

  • A bit of humor

  • End of lecture on 28 February 2005

  • Conditional constructsProvideAbility to control whether a statement list is executed

    Two constructs

    If statementifif-elseif-else-if

    Switch statement

  • Basic if statementSyntaxif (Expression) Action

    If the Expression is true then execute Action

    Action is either a single statement or a group of statements within braces

    For us, it will always be a group of statements within braces

  • Exampleif (value < 0) { value = -value;}

  • Sorting two valuesSystem.out.print("Enter an integer number: ");int value1 = stdin.nextInt();System.out.print("Enter another integer number: ");int value2 = stdin.nextInt();

    // rearrange numbers if necessaryif (value2 < value1) {// values are not in sorted orderint rememberValue1 = value1;value1 = value2;value2 = rememberValue1;}// display valuesSystem.out.println("The numbers in sorted order are "+ value1 + " and then " + value2);What happens if the user enters 11 and 28?

    What happens if the user enters 11 and 4?

  • If semantics

  • What an if statement executesAn 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 (!!!);}

  • Why we always use bracesWhat is the output?

    int m = 5;int n = 10;

    if (m < n) ++m;++n;

    System.out.println(" m = " + m + " n = " n);

  • Quick surveyI felt I understood the if statementVery wellWith some review, Ill be goodNot reallyNot at all

  • Todays demotivators

  • The if-else statementSyntaxif (Expression) Action1 else Action2

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

  • Finding the maximum of two valuesSystem.out.print("Enter an integer number: ");int value1 = stdin.nextInt();System.out.print("Enter another integer number: ");int value2 = stdin.nextInt();

    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);

    But is it initialized?

  • Finding the maximum of two values

  • Why we use whitespaceWhat 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);

  • 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 {//...}

  • Quick surveyI felt I understood the if-else statementVery wellWith some review, Ill be goodNot reallyNot at all

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

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

  • If-else-ifConsiderif (number == 0) {System.out.println("zero");}elseSystem.out.println("positive");}else { System.out.println("negative");}}{These braces arent neededif (number > 0) {Same results as previous segment but this segment better expresses the meaning of what is going onWe can change the whitespace of the code

  • Quick surveyI understand if-else-ifVery wellWith some review, Ill be goodNot reallyNot at all

  • Review of HW J4

  • Sorting three valuesFor sorting values n1, n2, and n3 there are six possible orderingsn1 n2 n3n1 n3 n2n2 n1 n3n2 n3 n1n3 n1 n2n3 n2 n1

    Suppose s1, s2, s3 are to be a sorted version of n1, n2, and n3

  • Sorting three valuesif ((n1
  • Finding the minimum valueConsider:

    // z is to hold the minimum of x and yif ( x < y )z = x;elsez = y;

    Another way to do this:

    z = (x

  • The ?: notationOnly works when both cases return a value!Example: z = (x
  • Switch statementSoftware engineers often confronted with programming tasks where required action depends on the values of integer expressionsThe if-else-if construct can be usedSeparately compare the desired expression to a particular valueIf the expression and value are equal, then perform the appropriate action

    Because such programming tasks occur frequentlyJava includes a switch statementThe task is often more readable with the switch then with the if-else-if

  • A switch statement exampleif (a == 0)System.out.println (zero);else if (a == 1)System.out.println (one);else if (a == 2)System.out.println (two);else if (a == 3)System.out.println (three);else if (a == 4)System.out.println (four);elseSystem.out.println (five+);switch (a) {case 0:System.out.println (zero);break;case 1:System.out.println (one);break;case 2:System.out.println (two);break;case 3:System.out.println (three);break;case 4:System.out.println (four);break;default:System.out.println (five+);break;}

  • Switch statement

  • Testing for vowel-nessswitch (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;default: System.out.println("not a vowel);}The break causes an exiting of the switchHandles all of the other cases

  • A better way to format that switch statementswitch (ch) {case 'a': // FALL THRUcase 'A':// FALL THRUcase 'e': // FALL THRUcase 'E':// FALL THRUcase 'i': // FALL THRUcase 'I':// FALL THRU

    ...

  • Processing a requestSystem.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);}

  • Quick surveyI understand the switch statementVery wellWith some review, Ill be goodNot reallyNot at all

  • Biggest software errorsAriane 5 rocket explosion (1996)Due to loss of precision converting 64-bit double to 16-bit intPentium division error (1994)Due to incomplete look-up table (like an array)Patriot-Scud missile error (1991)Rounding error on the timeThe missile did not intercept an incoming Scud missile, leaving 28 dead and 98 woundedMars Climate Orbiter (1999)Onboard used metric units; ground computer used English unitsAT&T long distance (1990)Wrong break statement in C codeTherac-25, X-ray (1975-1987)Badly designed software led to radiation overdose in chemotherapy patientsNE 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

  • End of lecture on 2 March 2005

  • Testing objects for equalityConsider

    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?

  • Testing objects for equalityConsider

    String s1 = pastel;String s2 = s1;

    if (s1 == s2) {System.out.println("Same");}else {System.out.println("Different");}

  • Testing objects for equality

    Memory looks like

    The comparison is between the references!

    Thus, s1 and s2 are the same (they refer to the same object)

  • Testing objects for equalityConsider

    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?

  • Testing objects for equalityWhen it is executedSystem.out.print("Enter a string: ");String s1 = stdin.nextLine();System.out.print("Enter another string: ");String s2 = stdin.nextLine();

    Memory looks like

    As a result no matter what is entered s1 and s2 are not the sameThey refer to different objects

  • Comparing strings for equalityConsider: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?falseHuh?

  • Testing operators for equalityConsiderSystem.out.print("Enter a string: ");String s1 = stdin.nextLine();System.out.print("Enter another string: ");String s2 = stdin.nextLine();

    if (s1.equals(s2)) {System.out.println("Same");}else {System.out.println("Different");}Tests whether s1 and s2 represent the same objectAll classes have a method equals(). Their implementation is class-specific. The String equals() method like many others tests for equivalence in representation

  • Assignment vs. comparison= is the assignment operatorIt copies the value on the right to the location on the leftConsider:int x;x = 5;The value 5 is copied to the spot x in memory

    == is the comparison operatorReturns a boolean (true or false) if the two sides are equalConsider:int x = 5;System.out.println (x == 5);System.out.println (x == 6);Prints out true, false

  • Some handy Character class methodsisDigit()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

  • Some handy Character class methodsisUpperCase()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

  • Quick surveyI understand comparing Strings and assignment vs. comparisonVery wellWith some review, Ill be goodNot reallyNot at all

  • Why speling is not so importantI 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.

  • Short-circuit evaluationThe value of a logical expression can be known before all the operands have been consideredIf left operand of && is false, then the value must be falseIf right operand of || is true, then the value must be true

    Java uses these properties to make logical operations efficientEvaluates left operand before it evaluates right operandIf the operator value is determined from the left operand, then the right operand is not evaluatedThe operation is short-circuited

  • Short-circuit evaluationShort-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 valueThe condition can be evaluated only if nbrScores is nonzero

    The following expression correctly represents the condition (nbrScores != 0) && ((scoreSum / nbrScores) > value)

  • class ShortCircuit { static boolean returnsFalse() {System.out.println ("returnsFalse() called");return false; } static boolean returnsTrue() {System.out.println ("returnsTrue() called");return true; }

    public static void main (String args[]) {

    if ( returnsFalse() && returnsTrue() ) {}

    if ( returnsTrue() && returnsFalse() ) {}

    if ( returnsFalse() || returnsTrue() ) {}

    if ( returnsTrue() || returnsFalse() ) {}

    }}returnsFalse() called

    returnsTrue() calledreturnsFalse() called

    returnsFalse() calledreturnsTrue() called

    returnsTrue() calledOutput

  • A digression: PerlPerl 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

  • Quick surveyI understand short circuit evaluationVery wellWith some review, Ill be goodNot reallyNot at all

  • All your base are belong to us

    Flash animationReference: http://en.wikipedia.org/wiki/All_your_base_are_belong_to_us

  • A Circle classWe are going to develop a Circle classPerhaps for use in a graphics program

    Why?Partly to review creating classesGo over some topics that were a bit fuzzyConstructors and creating objectsShow why one uses the get/set methods instead of directly modifying the instance variables

  • Circle class propertiesWhat properties does a circle have?RadiusPI = 3.141592653589793234Color (if plotting in a graphics program)(x,y) location

    These properties will become instance variablesWe are only going to play with the first two (radius and PI) in this exampleThus, we are ignoring the color and location

  • Our Circle classpublic class Circle {double radius;double PI = 3.1415926536;}Note the fieldsare not staticNote the radius field is not initialized by usWere ignoring the public for now

  • Accessing our Circle objectAny variable or method in an object can be accessed by using a periodThe 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)

  • 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);}}

    When a variable is declared as part of a method, Java does not initialize it to a default valueJava will give a variable not initialized error

  • 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);}}

    When a variable is declared as part of a class, Java does initialize it to a default valueJava outputs 0.0!

  • Whats going on?A (method) variable needs to be initialized before it is usedUsually called a local variableA instance variable is automatically initialized by JavaAll numbers are initialized to 0, booleans to false, etc.This is a bit counter-intuitive

  • Circle class behaviorsWhat do we want to do with (and to) our Circle class?Create circlesModify circles (mutators)Find out about our circles properties (accessors)Find the area of the circlePlot it on the screen (or printer)A few others

    These will be implemented as methods

  • Calling the Circle constructorTo create a Circle object:

    Circle c1 = new Circle();

    This does four things:Creates the c1 referenceCreates the Circle objectMakes the c1 reference point to the Circle objectCalls the constructor with no parameters (the default constructor)

    The constructor is always the first method called when creating (or constructing) an object

  • Calling the Circle constructorTo create a Circle object:

    Circle c1 = new Circle(2.0);

    This does four things:Creates the c1 referenceCreates the Circle objectMakes the c1 reference point to the Circle objectCalls the constructor with 1 double parameters (the specific constructor)

    The constructor is always the first method called when creating (or constructing) an object

  • ConstructorsRemember, the purpose of the constructor is to initialize the instance variablesPI 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 constructorsNote that the constructorname is the EXACT sameas the class nameNote that there are two methods with the same name!

  • Quick surveyHow are we doing with constructors?I totally got itIts making a lot more sense nowIm still a bit confusedI have no idea what you were talking about

  • Demotivators

  • What happens in memoryConsider: Circle c = new Circle();A double takes up 8 bytes in memoryThus, a Circle object takes up 16 bytes of memoryAs it contains two doublesShorthand representation

  • Consider the following codepublic class CircleTest {public static void main (String[] args) { Circle c1 = new Circle();Circle c2 = new Circle();Circle c3 = new Circle();Circle c4 = new Circle();}}

  • What happens in memoryThere are 4 Circle objects in memoryTaking up a total of 4*16 = 64 bytes of memory

  • Consider the following codepublic class CircleTest {public static void main (String[] args) { Circle c1 = new Circle();//...Circle c1000000 = new Circle();}}This program creates 1 million Circle objects!

  • What happens in memoryThere are 1 million Circle objects in memoryTaking up a total of 1,000,000*16 16 Mb of memoryNote that the final PI field is repeated 1 million times

  • The use of static for fieldsIf a variable is static, then there is only ONE of that variable for ALL the objectsThat variable is shared by all the objectsTotal memory usage: 8 Mb + 8 bytes (1,000,000+1=1,000,001 doubles)Total memory usage: 16 bytes (1+1=2 doubles)Total memory usage: 40 bytes (4+1=5 doubles)c1000000c4PI3.1415926536

  • More on static fieldsWhat does the following printNote 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);

    It prints 4.3Note you can refer to static fields byobject.variable

  • Even more on static fieldsThere is only one copy of a static field no matter how many objects are declared in memoryEven if there are zero objects declared!The one field is common to all the objects

    Static variables are called class variablesAs there is one such variable for all the objects of the classWhereas non-static variables are called instance variables

    Thus, you can refer to a static field by using the class name:Circle.PI

  • Even even more on static fieldsThis 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);

  • Even even even more on static fieldsWeve 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)

  • Quick surveyHow are we doing with static fields?I totally got itMore or lessIm still a bit confusedI have no idea what you were talking about

  • How much will Christmas cost?

    http://www.pncbank.com/12daysFlash animation (local)

  • Back to our Circle classpublic class Circle {double radius;final static double PI = 3.1415926536;

    public Circle() {radius = 1.0;}

    public Circle (double r) {radius = r;}

    }

    But it doesnt do much!Note that PI is now final and static

  • Adding a methodpublic 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

  • Using that methodpublic class CircleTest {public static void main (String[] args) {Circle c = new Circle();c.radius = 2.0;System.out.println (c.computeArea()); }}Prints 12.566370614356

  • End of lecture on 14 March 2005Actually ended 2 slides ahead, but I want to start up here

  • Review of our Circle classpublic class Circle {

    double radius;final static double PI = 3.1415926536;

    public Circle() {}

    public Circle (double r) {radius = r;}

    double computeArea () { return PI*radius*radius; }

    }Slight change from before

  • Adding another methoddouble oneOverRadius() { return 1.0/radius;}

    I couldnt think of a good reason to divide something by the radius

  • What happens now?Code in class CircleTests main() method

    Circle c = new Circle(); // c.radius is now 0.0System.out.println (c.oneOverRadius());

    Java wont crash, but many other programming languages (C and C++, in particular) willSo well call this a crash for the sake of this lecture

    Java prints InfinityNot what we wanted, though!

  • One way to fix thispublic class Circle {double radius = 1.0;final static double PI = 3.1415926536;

    // Constructors...

    double computeArea () { return PI*radius*radius; }

    double oneOverRadius() { return 1.0/radius;}

    }Note that the radius variable is now initialized to 1.0

  • Back to our programThis code will now run properly:

    Circle c = new Circle(); // c.radius = 1.0System.out.println (c.oneOverRadius());

    But this code will crash:

    Circle c = new Circle(); // c.radius = 1.0c.radius = 0.0;System.out.println (c.oneOverRadius());

  • Where the crash occurspublic class CircleTest {

    public static void main (String[] args) {

    Circle c = new Circle(); // c.radius = 1.0

    c.radius = 0.0;

    System.out.println (c.oneOverRadius());}}public class Circle {double radius = 1.0;final static double PI = 3.1415926536;

    double computeArea () { return PI*radius*radius; }

    double oneOverRadius() { return 1.0/radius;}

    Here is the badly written codeHere is where the crash occurs

  • Motivation for private fieldsProblem: 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 fieldGive it private visibility

    private means that only code within the class can modify the field

  • One way to fix thispublic 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;}

    }Note that the radius variable is now private

  • Back to our programThis code will now not compile:

    Circle c = new Circle(); // c.radius = 1.0c.radius = 0.0;System.out.println (c.oneOverRadius());

    Java will give a compile-time error:radius has private access in Circle

  • Back to our programThis code will also not compile:

    Circle c = new Circle(); // c.radius = 1.0System.out.println (c.radius);

    Java will give the same compile-time error:radius has private access in Circle

  • The problem nowBut 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;}

  • Our Circle class so farpublic 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; }}

  • Using the get/set methodspublic class CircleTest {

    public static void main (String[] args) {

    Circle c = new Circle();

    c.setRadius (1.0);

    System.out.println (c.computeArea());

    System.out.println (c.getRadius());

    }}public class Circle { private double radius = 1.0; final static double PI = 3.1415926536;

    double computeArea () { return PI*radius*radius; }

    double oneOverRadius() { return 1.0/radius; }

    void setRadius (double r) { radius = r; } double getRadius () { return radius; }}Here a method is invokedHere 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);

    System.out.println (c.oneOverRadius());

    }}Here is the problem now

  • This problem is easily fixedChange 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

  • Visibilities in JavaThere are four visibilities:private: Only code within the same class can access the field or methodNote: access means reading or writing the field, or invoking the method

    public: Any code, anywhere, can access the field or method

    protected: Used with inheritanceWe wont get to that this semester

    default: Almost the same as publicThis is the default (duh!)Note that it cant be specified like the others

  • A few notes on visibilitiesYou can NOT specify visibilities for method variablesAny method variable can only be accessed within that methodThink of it as public within the method (after its defined) and private outside the method

    You can also specify visibilities for methods and classesWe wont get to that in this course

  • Quick surveyI understand visibilities in JavaVery wellWith some review, Ill be goodNot reallyNot at all

  • Todays demotivators

  • Overriding methods (and constructors)Consider the following code:

    Circle c1 = new Circle (); Circle c2 = new Circle (2.0);

    Java knows which constructor to call by the list of parametersThis is called overloadingMeaning it means multiple things, depending on the context

    Weve seen overloading before:3+4Performs integer addition3.0+4.0Performs floating-point addition3+4Performs string concatenation

    The + operator is overloadedCreates a Circleof radius 1.0Creates a Circleof radius 2.0

  • Overriding methods (and constructors), take 2The 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; }

    public Circle (double p) { PI = p; }When Circle(1.0) is called, which one is meant?

  • Using mutators in the constructorOur 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)

  • Using mutators in the constructorThis 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)

  • Why we always use the mutatorsConsider 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

  • End of lecture on 16 March 2005Also did the first 20 (or so) slides of the slide set for chapter 6

  • Back to the static discussionRemember 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 objectIn this example, it doesnt read/write the radius

    In fact, that particular method doesnt care anything about the objects declaredIts only accessing a static field

  • Make getPI() staticConsider 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 objectExamples: Math.sin(), Math.tan(), Math.cos()They dont care about the state of any Math objectThey only perform the computation

  • Invoking static methodsAs 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

  • static methods and non-static fieldsConsider 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()); }

  • What happening in memoryThere are 4 Circle objects in memory

    Which radius field does Circle.getRadius() want?There are 1 million Circle objects in memoryThere are no Circle objects in memoryc1000000c4PI3.1415926536

  • The main static lessonA 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!

  • static and non-static rulesNon-static fields and methods can ONLY be accessed by the object nameStatic fields and methods can be accessed by EITHER the class name or the object nameNon-static methods can refer to BOTH static and non-static fieldsStatic methods can ONLY access static fields of the class they are part of

  • Back to our main() method public static void main (String[] args)

    Any code anywherecan call this methodIts a static method:Cant access non-static fields or methods directlyCan be called only by the class nameThe method does not return a valueWell learn about arrays in chapter 8

  • Quick surveyI felt I understood the material in this slide setVery wellWith some review, Ill be goodNot reallyNot at all

  • Quick surveyThe pace of the lecture for this slide set wasFastAbout rightA little slowToo slow

  • Quick surveyHow interesting was the material in this slide set? Be honest!Wow! That was SOOOOOOO cool!Somewhat interestingRather boringZzzzzzzzzzz

  • Sidewalk chalk guySource: http://www.gprime.net/images/sidewalkchalkguy/