T1 /Java OOP Yet again, with Kasper B. Graversen.
-
date post
22-Dec-2015 -
Category
Documents
-
view
217 -
download
0
Transcript of T1 /Java OOP Yet again, with Kasper B. Graversen.
T1 /Java OOPT1 /Java OOPYet again,Yet again, with Kasper B. Graversen with Kasper B. Graversen
Today’s planToday’s plan
• Number representation
• Logic operators and % operator
• Operator precedence
• Type casting
• JavaDoc
• Flow control
• Objects representing amounts
Nerdy, weirdeven boring!But necessary.
Useful and exciting - Stay awake!
On the right trackOn the right track
•The main properties of an object (instantiation, methods, attributes)
•The creation of objects with pointers pointing to them
•The difference between simple types and objects
DictionaryDictionary
• StaticStaticAccess to methods without object creation, only allowed in main() at this stage of the course!
•Constructor“method” automatically called at object creation
•“.” - Dot operatorAccess to attributes and methods in objects
Representation
100101 < 38== 26Binary Decimal Hexadecimal
37
Representation
1234
ones
tens
hundreds
thousands
100101one’s
two’sfour’s
eight’ssixteen’s
thirty-two’s
Formally:4*10 + 3*10 + 2*10 + 1*101 20 3
Equally:1*2 + 0*2 + 1*2 + 0*2 +...0 1 2 3
Representation
•Numbers are represented by bits.
•37 = 100101 , here rep. by 6 bits
•as int in Java (32 bit) =00000000 00000000 00000000 00100101
• Ranges of int:2 = 4.294.967.296 = ~-2.1 to ~2.1 billion
32
RepresentationRepresentation
•So, is a 64 bit number twice the size of a 32 bit number?
•No, the size grows exponentially, the range doubles for each new bit, ie. 1, 2, 4, 8, 16
•64 bit ~ 1,8*10
19
Calculations w. binary Calculations w. binary numbersnumbers
11001 + 0101 =11110
25
+ 5= 30
Representation of special Representation of special charschars
•How do we represent a ‘return’?– \b backspace
– \t tab
– \n linefeed
– \" double quote, "
– \' single quote, '
– \\ backslash, \System.out.println(”\”hello world\””);
•In programming ambiguity is forbidden, so we assign priorities to all the operators•With “(“ “)” we can change the order of evaluation to:
Operator precedenceOperator precedence
• What is 2+3*4 evaluated to? 14 or 20
+
2 3
4
*
+
2
3 4
*
Operator precedenceOperator precedence
• This is possible since () has the highest evaluation priority.
• Removing unnecessary () can clear up an expression
• To beginners () are clearer.
Operator precedenceOperator precedence1. ( )
2. *, /, % Multiplicative operators
3. +, - Additive operators
4. <, >, >=, <= Relational operators
5. ==, != Then do any comparisons for equality and inequality
6. & Bitwise and
7. | Bitwise or
8. && Logical and
9. || Logical or
10. ? : Conditional operator
11. = Assignment operator
Logic operatorsLogic operators
• Programs usually check for more than one condition.
• A bank account systemint withdraw(int dollars){ if(dollars > 0) { if(balance > dollars) { balance -= dollars; return balance; } }}
Tiresome!
if(dollars > 0 && balance > dollars){
balance -= dollars;return balance;
}
Logic operatorsLogic operators
• Don’t use |, & or ^ they are bitwise operators
• && AND || OR ! NOT
• “Not both Pinocchio and Santa”
!(Pinocchio && Santa)
•Any milk: non fat, low fat, regular
nonfat || lowfat || regular
Logic operatorsLogic operators
•The operators are very expressive.
•If v1,v2,v3 are “votes” when is the expression true?
(v1 && (v2||v3)) || (v2 && v3)
•The expression is true if at least two of the three votes are true
Alternative to logical op.Alternative to logical op.
•Another approach would be to count the votes manuallyint votes = 0;
if(v1) votes++;
if(v2) votes++;
if(v3) votes++;
if(votes >= 2)
{
}
if(v1 && (v2||v3) || v2 && v3) {
}
The % operatorThe % operator•The % (called modulus) returns
the remainder of a division.
•15/3 == 5 15%3 == 0
17/3 == 5 17%3 == 2
•xxx%3 returns numbers ranging 0-2
•How do we find out if number X is odd or even?
if(x%2 == 0) …if(x%2 == 1) …
Types and castingTypes and casting
•Explicit type casting
–simple types
–objects
•implicit type declaration (by syntax)
Explicit type castingExplicit type casting
•Formally: (Type) Expression– (int) 2.0
– (Horse) foo
•Inserted everywhere
– In parameters to method calls
– In front of method calls to alter return type
Explicit type castingExplicit type casting
• Its needed when loss of data may occur, ie double put into an integer– int i = 9.0/4.0 (compiler error)
– int i = (int) 9.0/4.0
•Problems arise especially when types are intermixed– 1/2*3.5 = 0.0– 1.0/2*3.5 = 1.75
Explicit type castingExplicit type casting
•Its needed when methods require other type of data than you have– double amount = 9.95;
withdraw(amount);
Must be changed to
withdraw((int)amount);
Implicit type declarationImplicit type declaration• 1 int
• 1L long
• 1.0 double
• 1.0ffloat
• ‘c’ char
• “c” String (object!)
• 01 Octal numbers!!!!
Implicit type declarationImplicit type declaration
•Two rare examplesWhat number does the following program print and why?
int a = 1000;int b = 0010;System.out.print(a-b);
Answer: 992
byte b1 = 2, b2 = 3, b3;b3 = b1 + b2;possible loss of precisionfound : intrequired byte b3 = b1 + b2; ^1 error
b3 = (byte)((int)b1 + (int)b2);
Control Of FlowControl Of Flow
•In java there are many possibilities of controlling the flow of the program. We will look at –if-else–for()
Control Of Flow: if-elseControl Of Flow: if-else
•We can branch the codecondition
thenstatements(code)
“meet at work”
if(floor.isDirty()){ floor.clean();}
“do the baking”
“meet at work”
“do the baking”
truefalse
Control Of Flow: if-elseControl Of Flow: if-else
•Sunday baker…if(day == sunday){ baker.makeDow(); Loaf l = baker.makeLoaf(); oven.insert(l); …}else{ baker.go(home);}…
condition
thenstatements(code)
true false
elsestatements(code)
Control Of Flow: if-elseControl Of Flow: if-else•What is the difference?
if(condition1){ statements1
}else if(condition2) { statements2
}else if(condition3) { statements3
}else { statements4
}
if(condition1){ statements1
}if(condition2) { statements2
}if(condition3) { statements3
}else { statements4
}
Dating for engineersDating for engineersint age;
System.out.print("How old are you: ");
age = Integer.parseInt(stdin.readLine());
if (age < 18)
System.out.print("Do you have an older sister/brother?");
else
if (age < 25)
System.out.print("Doing anything tonight?");
else
if (age < 35)
System.out.print("Do you have an younger sister/brother?");
else
if (age < 65)
System.out.print("Do you have a daughter/son?");
else
System.out.print("Do you have a granddaughter/grandson?");
-Andrew Taylor
How does the program run when ages 16 and 27 are met?
Control Of Flow: forControl Of Flow: for
•Loops are used to solve jobs which consist of one or more sub-jobs repeated.
–Reading a file a line at a time
–Interrogate all the suspects one by one
Control Of Flow: forControl Of Flow: for
•The syntaxinitial
statements
next
conditionfalse
truefor(initial ; condition ; next){ statements… }
Counting to 13int i;for(i = 0; i < 13; i++){ System.out.println(i);}
Why not int i = 0 instead of i = 0
““Quick Tips”Quick Tips”
•Creating the “quick tips” machine–There are 13 football matches a week
–Each match can either be won by either team or a draw, which is denoted 1, 2 or X
““Quick Tips”Quick Tips”
•A computer definition
–Do something 13 times
–At each time randomly find either 1, 2 or x
How do we do this?
Using random numbersUsing random numbers
•The javadoc explains• public static double random()
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
•The javadoc tophttp://java.sun.com/j2se/1.3/docs/api/index.html
http://java.sun.com/j2se/1.3/docs/api/java/lang/Math.html
““Quick Tips”Quick Tips”
•So (int) Math.random()*100
yields numbers from 0-100• (int)(Math.random()*100%3)
yields numbers from 0-2
““Quick Tips”Quick Tips”
The final programfor(int i = 0; i < 13; i++){ System.out.print(“Row “ +(i+1)+ “:”); int val = (Math.random()*100)%3; if(val == 0) System.out.println(“x”); else System.out.println(val);}
Why the green parenthesis?
Typed methodsTyped methods
•Are like methods, now they just return a value of a certain type
–Allows functionality which do more than print on the screen
–Allows splitting up a complex method into several sub-methods.
Typed methodsTyped methods
• FormallyreturnType methodName(Type input,…)
{
…
return someThingOfTheType;
}
• int celsiusToFarenheit(int celsius)
{
double fh = celsius * 9.0 / 0.5 + 32;
return Math.round((float) fh);
}
Typed methodsTyped methods•For our horse example from last
time:• class HorseEvaluator
{ /** return 0-100 where 100 is a super horse */
int evaluate(Horse h)
{
int grade; … ; return grade;
}
}
• class HorseDealer
{
HorseEvaluator friend;
void buyHorses()
{
for(int i = 0; i < noHorses; i++)
if(friend.evaluate(hx) > 90)
buyThatHorse();
} }
Typed methodsTyped methods
•If the horse evaluator only printed strings on the screen, the horse buyer could not ask for his advice!
Objects representing Objects representing amountsamounts
•We are to create a web store
•The store sells promotion pens, shirts and mugs
Objects representing Objects representing amountsamounts
•Last time we looked at objects representing one item, ie. a horse.
•We looked at how to represent the horse and especially which attributes should be used in the program
Objects representing Objects representing amountsamounts
•Each item in the store can be modeled as
–A name
–A description
–A price
Objects representing Objects representing amountsamounts
•We can design the shop either as
Shop
Accountingboolean sell(int no)
shirts pens mugs
Shop
Accountingboolean sell(int no)
numberLeftdescriptionprice
or
Objects representing Objects representing amountsamounts
•We must always balance between a too simplistic and a too complex model of the world.
•This should be evaluated against the current use of the program - as well as future use
String representation of String representation of objectsobjects
Horse h = new Horse(“Silas”,2);System.out.print(h);
A@73d6a5
• To make a better representation of an object, create a special toString() method
String representation of String representation of objectsobjects
class Horse{ … public String toString() { String s = “name: ”+name; s = s + “ energy: “ +energy; return s; }}
System.out.print(h) Will now give us more meaningful information
OOP in JavaOOP in Java
The end