Download presentation
Presentation is loading. Please wait.
1
Decisions, decisions, decisions
Chapter 5 Spring 2005 CS 101 Aaron Bloomfield
2
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.“); }
3
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
4
Logical expressions The branch of mathematics dealing with logical expressions is Boolean algebra Developed by the British mathematician George Boole
5
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
6
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
7
Quick survey I’ve seen Boolean logic before… Lots and lots and lots
A fair amount Some Not really
8
More demotivators
9
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 False False True False True False False True True True
10
Or and not truth tables p q p or q False False False False True True
True False True True True True p not q False True True False
11
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 False True False True False True True False False True True True True False
12
DeMorgan’s laws not (p and q) equals (not p) or (not q)
(not p) or p q p and q not (p and q) ( not p) (not q) (not q) False False False True True True True False True False True True False True True False False True False True True True True True False False False False
13
DeMorgan’s laws not (p or q) equals (not p) and (not q)
(not p) and p q p or q not (p or q) ( not p) (not q) (not q) False False False True True True True False True False False True False False True False False False False True False True True True False False False False
14
DeMorgan’s 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)
15
A boolean type Java has the logical type boolean
Type boolean has two literal constants true false Operators The and operator is && Don’t use & The or operator is || Don’t use | The not operator is !
16
Defining boolean variables
Local boolean variables are uninitialized by default boolean isWhitespace; boolean receivedAcknowledgement; boolean haveFoundMissingLink;
17
Defining boolean variables
Local boolean variables with initialization boolean canProceed = true; boolean preferCyan = false; boolean completedSecretMission = true;
18
Defining boolean variables
Instance boolean variables are initialized to false by default boolean isWhitespace; boolean receivedAcknowledgement; boolean haveFoundMissingLink; false isWhitespace receivedAcknowledgement haveFoundMissingLink
19
DeCSS: The program #include<stdlib.h> typedef unsigned int uint; char ctb[512]="33733b b763e7e362b6e2e667bd393db b96de9ed60b4e0e4\ 69b57175f82c787cf125a1a528fca8ac21fd999d d898d d7d35246\ d2d65743c7c34256c2c6475dd9dd5044d0d4594dc9cd4054c0c c989c \ 081c888c011d797df f92da9ad20f4a0a429f53135b86c383cb165e1e568bce8ec61bb\ 3f3bba6e3a3ebf6befeb6abeeaee6fb37773f f723a7a322f6a2a627fb9f9b1a0e9a9e\ 1f0b8f8b0a1e8a8e0f15d1d5584cd8dc5145c1c5485cc8cc415bdfdb5a4edade5f4bcfcb4a5e\ cace4f b7f7bfa2e7a7eff2bafab2afeaaae2ff"; 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);}
20
DeCSS: The shirt (and tie!)
21
DeCSS: The poem How to decrypt a Table Zero is: 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
22
DeCSS: The number The world’s first illegal prime number:
23
DeCSS: The images
24
DeCSS: The recordings All this info from Or do a Google search for “decss gallery”
25
DeCSS: The movie
26
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
27
Evaluating boolean expressions
Suppose boolean p = true; boolean q = false; boolean r = true; boolean s = false; What is the value of p p && s !s p == q q q != r p && r r == s q || s q != s
28
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 != k i == j j != k c == e d != e c == d c != e
29
Floating point precission
What gets printed? class FloatTest { public static void main (String args[]) { double y = ; System.out.println (y); } FloatTest.java There are ’s
30
Take care with floating-point values
Consider double a = 1; double b = double c = ; 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
31
How to solve this Don’t 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 = ; boolean foo = Math.abs (a-b) < EPSILON;
32
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
33
Evaluation boolean expressions
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
34
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.
35
Evaluation boolean expressions
Suppose char c = '2'; char d = '3'; char e = '2'; What is the value of c < d c < e c <= e d >= e c >= e
36
Operator precedence revisited
Highest to lowest Parentheses Unary operators Multiplicative operators Additive operators Relational ordering Relational equality Logical and Logical or Assignment
37
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 semi-colon 5 circle.getRadius() x Note the difference between the following: ++i is an expression ++i; is a statement
38
Quick survey I felt I understood expressions Very well
With some review, I’ll be good Not really Not at all
39
A bit of humor…
40
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 For us, it will always be a group of statements within braces Expression Action true false
42
Example if (value < 0) { value = -value; } Is our number negative?
false Value < 0 Value = -Value true If Value is less than zero then we need to update its value to that of its additive inverse If Value is not less than zero then our number is fine as is Our number is now definitely nonnegative
43
Sorting two values What happens if the user enters 11 and 28?
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; } // display values System.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?
44
If semantics Are the numbers out of order Rearrange value1 and
value2 < value1 int rememberValue1 = value1 value1 = value2 value2 = rememberValue1 true false Are the numbers out of order Rearrange value1 and value2 to put their values in the proper order 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
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 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
The if-else statement Syntax if (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 Expression Action1 Action2 true false
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(); 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?
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 maximum = value2 maximum = value1 true false No, its not. So value1 is at least as large as value2. In this case, maximum is set to value1 Either case, maximum is set correctly
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 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"); else System.out.println("negative"); Which if does this else refer to?
56
If-then-else precedence without whitespace
if (number != 0) if (number > 0) System.out.println("positive"); else System.out.println("negative"); System.out.println("zero");
57
We can change the whitespace of the code These braces aren’t needed
If-else-if Consider We can change the whitespace of the code if (number == 0) { System.out.println("zero"); } else { These braces aren’t needed if (number > 0) { 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 I understand if-else-if… Very well
With some review, I’ll be good Not really Not at all
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)) { // n1 <= n2 <= n3 s1 = n1; s2 = n2; s3 = n3; } else if ((n1 <= n3) && (n3 <= n2)) { // n1 <= n3 <= n2 s1 = n1; s2 = n3; s3 = n2; else if ((n2 <= n1) && (n1 <= n3)) { // n2 <= n1 <= n3 s1 = n2; s2 = n1; s3 = n3; else if ((n2 <= n3) && (n3 <= n1)) { // n2 <= n3 <= n1 s1 = n2; s2 = n3; s3 = n1; else if ((n3 <= n1) && (n1 <= n2)) { // n3 <= n1 <= n2 s1 = n3; s2 = n1; s3 = n2; else { // n3 <= n2 <= n1 s1 = n3; s2 = n2; s3 = n1;
63
Finding the minimum value
Consider: // z is to hold the minimum of x and y if ( x < y ) z = x; else z = y; Another way to do this: z = (x<y) ? x : y; Notice no braces!
64
The ?: notation Only works when both “cases” return a value!
Example: z = (x<y) ? x : y; Thus, you can’t put a print statement in there! 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
switch (a) { case ‘0’: System.out.println (“zero”); break; case ‘1’: System.out.println (“one”); case ‘2’: System.out.println (“two”); case ‘3’: System.out.println (“three”); case ‘4’: System.out.println (“four”); default: System.out.println (“five+”); } if (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”); else System.out.println (“five+”);
67
Integral expression to
Switch statement Integral expression to be matched with a case expression switch ( SwitchExpression ) { case CaseExpression 1 : Action ; 2 ... n default +1 } Java statements Constant integral expression
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; default: System.out.println("not a vowel“); } The break causes an exiting of the switch Handles all of the other cases
69
A better way to format that switch statement
switch (ch) { case 'a': // FALL THRU case 'A': case 'e': case 'E': case 'i': case 'I': ...
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 I understand the switch statement… Very well
With some review, I’ll 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 ( ) Badly designed software led to radiation overdose in chemotherapy patients NE US power blackout (2003) Flaw in GE software contributed to it References:
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?
74
Testing objects for equality
Consider String s1 = “pastel”; String s2 = s1; if (s1 == s2) { System.out.println("Same"); } else { System.out.println("Different");
75
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) "pastel" s1 s2
76
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?
77
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 As a result no matter what is entered s1 and s2 are not the same They refer to different objects
78
Comparing strings for equality
Consider: String s = "hello"; String t = "hello"; System.out.println (s == t); What gets printed? true String u = new String("hello"); String v = new String("hello"); System.out.println (u == v); false Huh? These aren’t the exact same thing
79
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(); if (s1.equals(s2)) { System.out.println("Same"); } else { System.out.println("Different"); Tests whether s1 and s2 represent the same object All classes have a method equals(). Their implementation is class-specific. The String equals() method – like many others – tests for equivalence in representation
80
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 int x = 5; System.out.println (x == 5); System.out.println (x == 6); Prints out true, false
81
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
82
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
83
Quick survey I understand comparing Strings and assignment vs. comparison… Very well With some review, I’ll be good Not really Not at all
84
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.
85
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
86
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)
87
Output returnsFalse() called returnsTrue() called 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() ) { Output returnsFalse() called returnsTrue() called
88
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
89
Quick survey I understand short circuit evaluation… Very well
With some review, I’ll be good Not really Not at all
90
All your base are belong to us
Flash animation Reference:
91
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
92
Circle class properties
What properties does a circle have? Radius PI = 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
93
Our Circle class Note the radius field is not initialized by us
public class Circle { double radius; double PI = ; } c Circle radius = 0.0 - PI = … - … + … Note the fields are not static We’re ignoring the public for now
94
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; c Circle radius = 0.0 - PI = … - … + … This is bad – PI should have been declared final (this will be done later)
95
What’s the output? Java will give a “variable not initialized” error
public class Circle { double radius; double PI = ; } 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 value Java will give a “variable not initialized” error
96
What’s the output now? Java outputs 0.0! public class Circle {
double radius; double PI = ; } 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 value Java outputs 0.0!
97
What’s going on? A (method) variable needs to be initialized before it is used Usually called a local variable A instance variable is automatically initialized by Java All numbers are initialized to 0, booleans to false, etc. This is a bit counter-intuitive…
98
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
99
Calling the Circle constructor
To create a Circle object: 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) The constructor is always the first method called when creating (or ‘constructing’) an object c1 Circle radius = 0.0 - PI = … - … + Circle() + Circle (double r) + …
100
Calling the Circle constructor
To create a Circle object: 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) The constructor is always the first method called when creating (or ‘constructing’) an object c1 Circle radius = 0.0 - PI = … - … + Circle() + Circle (double r) + …
101
Note that the constructor
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!
102
Quick survey 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
103
Demotivators
104
Shorthand representation
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 Shorthand representation Circle radius = 1.0 - PI = - … + Circle() + Circle (double r) + … c c Circle radius = 1.0 - PI =
105
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(); }
106
What happens in memory There are 4 Circle objects in memory
Taking up a total of 4*16 = 64 bytes of memory c1 c2 c3 c4 Circle radius = 1.0 - PI = Circle radius = 1.0 - PI = Circle radius = 1.0 - PI = Circle radius = 1.0 - PI =
107
Consider the following code
public class CircleTest { public static void main (String[] args) { Circle c1 = new Circle(); //... Circle c = new Circle(); } This program creates 1 million Circle objects!
108
… 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 c … Circle radius = 1.0 - PI = Circle radius = 1.0 - PI = Circle radius = 1.0 - PI = Note that the final PI field is repeated 1 million times
109
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 Total memory usage: 8 Mb + 8 bytes (1,000,000+1=1,000,001 doubles) Total memory usage: 40 bytes (4+1=5 doubles) Total memory usage: 16 bytes (1+1=2 doubles) Circle radius = 1.0 c1 Circle radius = 1.0 c2 Circle radius = 1.0 c3 Circle radius = 1.0 c c4 … PI
110
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); It prints 4.3 Note you can refer to static fields by object.variable
111
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
112
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);
113
Even even even more on static fields
We’ve 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)
114
Quick survey 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
115
How much will Christmas cost?
Flash animation (local)
116
Back to our Circle class
public class Circle { double radius; final static double PI = ; public Circle() { radius = 1.0; } public Circle (double r) { radius = r; But it doesn’t do much! Note that PI is now final and static
117
Adding a method public class Circle { double radius; final static double PI = ; // Constructors... double computeArea () { return PI*radius*radius; } Note that a (non-static) method can use both instance and class variables
118
Using that method Prints 12.566370614356 public class CircleTest {
public static void main (String[] args) { Circle c = new Circle(); c.radius = 2.0; System.out.println (c.computeArea()); } Prints
119
Review of our Circle class
public class Circle { double radius; final static double PI = ; public Circle() { } public Circle (double r) { radius = r; double computeArea () { return PI*radius*radius; Slight change from before
120
Adding another method double oneOverRadius() { return 1.0/radius; } I couldn’t think of a good reason to divide something by the radius…
121
What happens now? Code in class CircleTest’s main() method
Circle c = new Circle(); // c.radius is now 0.0 System.out.println (c.oneOverRadius()); Java won’t crash, but many other programming languages (C and C++, in particular) will So we’ll call this a ‘crash’ for the sake of this lecture Java prints “Infinity” Not what we wanted, though!
122
One way to fix this… Note that the radius variable is now initialized to 1.0 public class Circle { double radius = 1.0; final static double PI = ; // Constructors... double computeArea () { return PI*radius*radius; } double oneOverRadius() { return 1.0/radius;
123
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”: c.radius = 0.0;
124
Where the “crash” occurs
public 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 = ; double computeArea () { return PI*radius*radius; } double oneOverRadius() { return 1.0/radius; Here is where the “crash” occurs Here is the badly written code
125
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: Don’t allow other code to modify the radius field Give it private visibility private means that only code within the class can modify the field
126
One way to fix this… Note that the radius variable is now private
public class Circle { private double radius = 1.0; final static double PI = ; // Constructors... double computeArea () { return PI*radius*radius; } double oneOverRadius() { return 1.0/radius;
127
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
128
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
129
The problem now… But now you can’t 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;
130
Our Circle class so far public class Circle {
private double radius = 1.0; final static double PI = ; // Constructors... double computeArea () { return PI*radius*radius; } double oneOverRadius() { return 1.0/radius; void setRadius (double r) { radius = r; double getRadius () { return radius;
131
Using the get/set methods
public class CircleTest { public static void main (String[] args) { Circle c = new Circle(); c.setRadius (1.0); System.out.println (c.computeArea()); (c.getRadius()); } public class Circle { private double radius = 1.0; final static double PI = ; 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 invoked Here the change to radius occurs
132
Wait! Another problem! Here is the problem now…
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…
133
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
134
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 won’t get to that this semester default: Almost the same as public This is the default (duh!) Note that it can’t be specified like the others
135
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 it’s defined) and private outside the method You can also specify visibilities for methods and classes We won’t get to that in this course
136
Quick survey I understand visibilities in Java… Very well
With some review, I’ll be good Not really Not at all
137
Today’s demotivators
138
Overriding methods (and constructors)
Creates a Circle of radius 1.0 Consider the following code: Circle c1 = new Circle (); Circle c2 = new Circle (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 We’ve seen overloading before: 3+4 Performs integer addition Performs floating-point addition “3”+”4” Performs string concatenation The ‘+’ operator is overloaded Creates a Circle of radius 2.0
139
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; public Circle (double p) { PI = p; When Circle(1.0) is called, which one is meant?
140
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)
141
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 won’t set it to zero)
142
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: That’s 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”; size = “huge”; }
143
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 doesn’t read or modify the “state” of any object In this example, it doesn’t read/write the radius In fact, that particular method doesn’t care anything about the objects declared It’s only accessing a static field
144
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 don’t care about the state of any Math object They only perform the computation
145
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
146
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());
147
What happening in memory
There are no Circle objects in memory There are 1 million Circle objects in memory There are 4 Circle objects in memory Which radius field does Circle.getRadius() want? Circle radius = 1.0 c1 Circle radius = 1.0 c2 Circle radius = 1.0 c3 Circle radius = 1.0 c c4 … PI
148
The main static lesson 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!
149
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
150
Back to our main() method
We’ll learn about arrays in chapter 8 public static void main (String[] args) 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
151
Quick survey I felt I understood the material in this slide set…
Very well With some review, I’ll be good Not really Not at all
152
Quick survey The pace of the lecture for this slide set was… Fast
About right A little slow Too slow
153
Quick survey How interesting was the material in this slide set? Be honest! Wow! That was SOOOOOOO cool! Somewhat interesting Rather boring Zzzzzzzzzzz
154
Sidewalk chalk guy Source:
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.