chapter 6 - decisions. characters char char primitive data type primitive data type stores a single...
Post on 26-Dec-2015
230 Views
Preview:
TRANSCRIPT
Chapter 6 - Chapter 6 - DecisionsDecisions
CharactersCharacters
charchar primitive data typeprimitive data type stores a single characterstores a single character operations operations (same as (same as intint)):: + -+ -
special chars special chars (use backslash)(use backslash)::''\\nn'' ''\\tt'' ''\\\\'' ''\\''''
ExampleExample char c = char c = ''aa'';;char q = char q = ''\\''''; // stores a single quote ; // stores a single quote
c
a
q
'
PracticePractice
int i = (int) 'D'
char c = (char) 106
i = 'D' + 'A'
c = (char)('D' + 42)
68
j
133
‘n’
Chapter GoalsChapter Goals To be able to implement decisions using To be able to implement decisions using
if statements if statements To understand how to group statements To understand how to group statements
into blocks into blocks To learn how to compare integers, To learn how to compare integers,
floating-point numbers, strings, and floating-point numbers, strings, and objects objects
To recognize the correct ordering of To recognize the correct ordering of decisions in multiple branches decisions in multiple branches
To program conditions using Boolean To program conditions using Boolean operators and variables operators and variables
ControlControl
The real world requires decisionsThe real world requires decisions Is it time to feed the cat? Can a book Is it time to feed the cat? Can a book
be checked out?be checked out? Essential feature of nontrivial programs Essential feature of nontrivial programs
is to make decisions based on inputis to make decisions based on input
The answers to these decision The answers to these decision require different actionsrequire different actions
Introduces the need for Introduces the need for control control statementsstatements
BooleanBoolean
booleanboolean is a primitive data type that is a primitive data type that holds one of two valuesholds one of two values truetrue falsefalse
Any time a question needs to be Any time a question needs to be asked, we use a boolean expression, asked, we use a boolean expression, which returns a boolean valuewhich returns a boolean value As apposed to a mathematical As apposed to a mathematical
expression which returns a number expression which returns a number valuevalue
Relational OperatorsRelational Operators
What operators are used for boolean What operators are used for boolean expressions?expressions?
<< less thanless than
<=<= less than or equal toless than or equal to
>> greater thangreater than
>=>= greater than or equal togreater than or equal to
==== equal toequal to
!=!= not equal tonot equal to
Boolean OperatorsBoolean Operators Boolean expressions are just like Boolean expressions are just like
mathematical expressionsmathematical expressions But here, they return a true or false But here, they return a true or false
(not int, double, etc)(not int, double, etc)
These are the 6 binary operatorsThese are the 6 binary operators
Ex.Ex. testScore < 80testScore < 80 testScore * 2 > 350testScore * 2 > 350
if statementif statement
Conditional statements are Conditional statements are represented with if-else statementsrepresented with if-else statements
Scanner stdin = new Scanner(System.in);Scanner stdin = new Scanner(System.in);int testScore = stdin.nextInt();int testScore = stdin.nextInt();
ifif (testScore < 70){ (testScore < 70){
System.out.println(“You are below the mean”);System.out.println(“You are below the mean”);
}}
else {else {
System.out.println(“You are above the mean”);System.out.println(“You are above the mean”);
}}
SyntaxSyntax
ifif (<boolean expression>){ (<boolean expression>){
<then block><then block>
}}
else{else{
<else block><else block>
}}
if statementsif statements When the code reaches the if statement, When the code reaches the if statement,
it evaluates the boolean expressionit evaluates the boolean expression
If it is true, the <then block> is executedIf it is true, the <then block> is executed
If it is false, the <else block> is executedIf it is false, the <else block> is executed
Called a Called a branching statementbranching statement because it because it branches to a block of codebranches to a block of code
BankAccountBankAccount Revisted Revisted
Withdraw method we implemented Withdraw method we implemented allowed user to withdraw as much allowed user to withdraw as much money as they wantedmoney as they wanted Is this realistic?Is this realistic?
What What decisiondecision should should withdraw()withdraw() make? make?
What should the decision be made on?What should the decision be made on?
Version 2.0Version 2.0
public void withdraw(double amount){public void withdraw(double amount){
if (amount <= balance)if (amount <= balance)
balance -= amount;balance -= amount;
}}
Simple vs. CompoundSimple vs. Compound The decision we have made only The decision we have made only
resulted in one instructionresulted in one instruction
Most decisions lead to a path of Most decisions lead to a path of instructions, requiring multiple instructions, requiring multiple statements. The statements are statements. The statements are grouped with curly braces{ } grouped with curly braces{ }
if (amount <= balance) {if (amount <= balance) {System.out.println(“Legal Withdrawal”);System.out.println(“Legal Withdrawal”);balance = balance – amount;balance = balance – amount;
}}else {else {balance = balance – OVERDRAFT_PENALTY;balance = balance – OVERDRAFT_PENALTY;
}}
Productivity Hint 6.1Productivity Hint 6.1 Style guide – use indentation to indicated Style guide – use indentation to indicated
nesting levelsnesting levelspublic class BankAccountpublic class BankAccount
{{
|| ……
|| public void withdraw()public void withdraw()
|| {{
|| || if (amount <= balance)if (amount <= balance)
|| || {{
|| || || balance -= amount;balance -= amount;
|| || }}
|| }}
}}
If statementIf statement If you have a single statement, { } not If you have a single statement, { } not
requiredrequiredifif (testScore < 70) (testScore < 70)
System.out.println(“You are below the mean”);System.out.println(“You are below the mean”);
elseelse
System.out.println(“You are above the mean”);System.out.println(“You are above the mean”);
But convention to use them anywaysBut convention to use them anyways Helpful for adding temporary output to check Helpful for adding temporary output to check
if a branch is executedif a branch is executed Makes nested if-else statements easier to Makes nested if-else statements easier to
read(later)read(later) Avoid errorsAvoid errors
DefinitionDefinition Simple StatementSimple Statement
Basic statement such as Basic statement such as balance = balance – amount;balance = balance – amount;
Block statementBlock statement – a group of statements – a group of statements enclosed within curly bracesenclosed within curly braces MethodsMethods ClassesClasses If statements, Switch, LoopsIf statements, Switch, Loops
Compound statementCompound statement Statements that have multiple paths of Statements that have multiple paths of
executionexecution If statements, loopsIf statements, loops
Syntax – if statementSyntax – if statement
if(if(conditioncondition)) statementstatement
if (if (conditioncondition)) statement1statement1
elseelse statement2statement2
statementstatement must be a statement - simple, must be a statement - simple, compound, or blockcompound, or block
Comparing integersComparing integers
Comparing whole numbers is Comparing whole numbers is trivialtrivial
int a = 5;int a = 5;
if (a == 5){if (a == 5){
System.out.println(“Wow this is easy!”);System.out.println(“Wow this is easy!”);
} else {} else {
System.out.println(“I wanna go home!”);System.out.println(“I wanna go home!”);
}}
Comparing Floating Comparing Floating PointPoint Comparing real numbers is more Comparing real numbers is more
difficult when taking into account difficult when taking into account roundoff errors.roundoff errors.
double r = Math.sqrt(2);double r = Math.sqrt(2);double d = r * r – 2;double d = r * r – 2;if (d != 0){if (d != 0){System.out.println(“Your equation is System.out.println(“Your equation is incorrect, the result is “ + d);incorrect, the result is “ + d);
}}
Your equation is incorrect, the result is Your equation is incorrect, the result is 4.440892098500626E-164.440892098500626E-16
RoundoffRoundoff
This is a problem, since logically the This is a problem, since logically the equation makes senseequation makes sense
Lesson: Floating point numbers may Lesson: Floating point numbers may not be exactnot be exact
Solution: Use range of values that can Solution: Use range of values that can be valuedbe valued Should be close to 0Should be close to 0
To avoid roundoff errors, don't use == To avoid roundoff errors, don't use == to compare floating-point numbers to compare floating-point numbers
To compare floating-point numbers To compare floating-point numbers test whether they are test whether they are close enoughclose enough: : ||xx - - yy| ≤ ε| ≤ ε final double EPSILON = 1E-14;final double EPSILON = 1E-14;if (Math.abs(x - y) <= EPSILON)if (Math.abs(x - y) <= EPSILON)// x is approximately equal to y // x is approximately equal to y
ε is a small number such as 10ε is a small number such as 10-14-14
ifif Statement Statement
if ( x == y )if ( x == y )
{{
System.out.print( "x equals System.out.print( "x equals y");y");
}}
In an In an ifif statement, statement, the block { } is only the block { } is only executed if the executed if the condition expressioncondition expressionis is truetrue. .
Indent stmts inside the block.
Example SetupExample Setup
// Declare and create Die objects// Declare and create Die objectsDie die1 = new Die();Die die1 = new Die();Die die2 = new Die();Die die2 = new Die();
// Roll die objects// Roll die objectsdie1.roll(); die1.roll(); die2.roll();die2.roll();
// Save results in new variables// Save results in new variablesint roll1 = die1.getTop();int roll1 = die1.getTop();int roll2 = die2.getTop();int roll2 = die2.getTop();
Simple Simple ifif Statement Statement
// Test for doubles// Test for doubles
if ( roll1 == roll2 ) {if ( roll1 == roll2 ) {
System.out.println( "Doubles" );System.out.println( "Doubles" );
}}
// rest of program// rest of program
Control Flow of If statementControl Flow of If statement
roll1 == roll2 System.out.println( “doubles!” );
... continue with rest of program
true
false
Simple Simple if-elseif-else Statement Statement
// Test for doubles// Test for doublesif ( roll1 == roll2 ) {if ( roll1 == roll2 ) { System.out.println( "Doubles" );System.out.println( "Doubles" );}}else {else { System.out.println("Sorry, no doubles");System.out.println("Sorry, no doubles");}}// rest of program// rest of program
Control Flow of Control Flow of if-elseif-else
roll1 == roll2 System.out.println( “doubles!” );
System.out.println( “sorry ...” );
... continue with rest of program
true
false
Advanced TopicAdvanced Topic
Selection OperatorSelection Operatorcondition ? value1 : value2condition ? value1 : value2
If the condition is true, If the condition is true, value1value1 is is returned. returned. value2 value2 if the condition false if the condition false
Ex. Absolute ValueEx. Absolute Valuey = (x >= 0) ? x : -x;y = (x >= 0) ? x : -x;
6.3 Multiple Alternatives6.3 Multiple AlternativesString r; String r; ifif (richter >= 8.0) (richter >= 8.0) {{
r = "Most structures fall"; r = "Most structures fall"; } else if} else if (richter >= 7.0) (richter >= 7.0) {{
r = "Many buildings destroyed"; r = "Many buildings destroyed"; } else if} else if (richter >= 6.0) (richter >= 6.0) {{
r = "Many buildings considerably damaged, some r = "Many buildings considerably damaged, some collapse"; collapse";
} else if} else if (richter >= 4.5) (richter >= 4.5) {{r = "Damage to poorly constructed buildings"; r = "Damage to poorly constructed buildings";
} else if } else if (richter >= 3.5) (richter >= 3.5) {{r = "Felt by many people, no destruction"; r = "Felt by many people, no destruction";
} else if} else if (richter >= 0) (richter >= 0) {{r = "Generally not felt by people"; r = "Generally not felt by people";
} else {} else {r = "Negative numbers are not valid";r = "Negative numbers are not valid";
}}
Multiple alternativesMultiple alternatives
First condition that is true is the First condition that is true is the ONLY statement executedONLY statement executed
Therefore, order mattersTherefore, order mattersifif (testScore >= 90) (testScore >= 90) {{
System.out.println(“Great!”);System.out.println(“Great!”);
} else if} else if (testScore >= 70) (testScore >= 70) {{System.out.println(“OK”);System.out.println(“OK”);
} else if} else if (testScore >= 50) (testScore >= 50) {{System.out.println(“D’oh!”);System.out.println(“D’oh!”);
}}
WRONG versionWRONG version
ifif (testScore >= 50) (testScore >= 50) {{
System.out.println(“D’oh!”);System.out.println(“D’oh!”);
} else if} else if (testScore >= 70) (testScore >= 70) {{
System.out.println(“OK”);System.out.println(“OK”);
} else if} else if (testScore >= 90) (testScore >= 90) { {
System.out.println(“Great!”);System.out.println(“Great!”);
}}
Else matters alsoElse matters also
ifif (testScore >= 90) (testScore >= 90)
System.out.println(“Great!”);System.out.println(“Great!”);
ifif (testScore >= 70) (testScore >= 70)
System.out.println(“OK”);System.out.println(“OK”);
ifif (testScore >= 50) (testScore >= 50)
System.out.println(“D’oh!”);System.out.println(“D’oh!”);
Not exclusive statements anymoreNot exclusive statements anymore
Adv 6.2 Switch Adv 6.2 Switch StatementStatement
switch ( < arithmetic expression>){switch ( < arithmetic expression>){
<case label 1>: <case body 1><case label 1>: <case body 1>
......
<case label n>: <case body n><case label n>: <case body n>
}}
Can only be used on integers, Can only be used on integers, characters, or enumerated constantscharacters, or enumerated constants
Good for testing multiple values for Good for testing multiple values for one expressionone expression
The The break break statement causes statement causes execution to skip the remaining execution to skip the remaining portion of the portion of the switchswitch statement and statement and resume execution following the resume execution following the switch switch statement. statement.
The The breakbreak statement is necessary to statement is necessary to execute statements in one and only execute statements in one and only one case.one case.
Switch statementSwitch statement
switch( c )//Some primitive{switch( c )//Some primitive{
case ‘y‘ : case ‘y‘ : System.out.println(“Yes”);System.out.println(“Yes”);
break;break;
case ‘n’ :case ‘n’ : System.out.println(“No”);System.out.println(“No”);
break;break;
defaultdefault : : System.out.println(“Invalid System.out.println(“Invalid entry”);entry”);
}}
6.3.2 Nested branches6.3.2 Nested branches
thenthen and and elseelse blocks can contain as blocks can contain as many statements as neededmany statements as needed
Can also have another if statement: Can also have another if statement: nested-if statementnested-if statement
ExampleExample
ifif (testScore >= 70) { (testScore >= 70) {
ifif (studentAge < 10) { (studentAge < 10) {
System.out.println(“You did a great job”);System.out.println(“You did a great job”);
} } else else {{
System.out.println(“You did pass”);System.out.println(“You did pass”);
//test score >=70 and age >=10//test score >=70 and age >=10
}}
} } elseelse { //test score < 70 { //test score < 70
System.out.println(“You did not pass”);System.out.println(“You did not pass”);
}}
Tax ScheduleTax Schedule
Compute taxes due, given filing status Compute taxes due, given filing status and income figure: and income figure:
(1)(1) branch on the filing statusbranch on the filing status
(2)(2) for each filing status, branch on income for each filing status, branch on income levellevel
The two-level decision process is The two-level decision process is
reflected in two levels of if statements reflected in two levels of if statements
We say that the income test is We say that the income test is nestednested inside the test for filing status inside the test for filing status
if (status == SINGLE)if (status == SINGLE) {{
if (income <= SINGLE_BRACKET1){if (income <= SINGLE_BRACKET1){
tax = RATE1 * income; tax = RATE1 * income;
} else if (income <= SINGLE_BRACKET2){} else if (income <= SINGLE_BRACKET2){
tax = RATE1 * SINGLE_BRACKET1 tax = RATE1 * SINGLE_BRACKET1
+ RATE2 * (income - SINGLE_BRACKET1); + RATE2 * (income - SINGLE_BRACKET1);
} else {} else {
tax = RATE1 * SINGLE_BRACKET1 tax = RATE1 * SINGLE_BRACKET1
+ RATE2 * (SINGLE_BRACKET2 -+ RATE2 * (SINGLE_BRACKET2 -SINGLE_BRACKET1) SINGLE_BRACKET1)
+ RATE3 * (income - SINGLE_BRACKET2);+ RATE3 * (income - SINGLE_BRACKET2);
}}
}}
else {else {
if (income <= MARRIED_BRACKET1){ if (income <= MARRIED_BRACKET1){
tax = RATE1 * income; tax = RATE1 * income;
} else if (income <= MARRIED_BRACKET2) {} else if (income <= MARRIED_BRACKET2) {
tax = RATE1 * MARRIED_BRACKET1 tax = RATE1 * MARRIED_BRACKET1
+ RATE2 * (income - MARRIED_BRACKET1); + RATE2 * (income - MARRIED_BRACKET1);
} else {} else {
tax = RATE1 * MARRIED_BRACKET1 tax = RATE1 * MARRIED_BRACKET1
+ RATE2 * (MARRIED_BRACKET2 - + RATE2 * (MARRIED_BRACKET2 - MARRIED_BRACKET1) MARRIED_BRACKET1)
+ RATE3 * (income - MARRIED_BRACKET2); + RATE3 * (income - MARRIED_BRACKET2);
}}
}}
Dangling elseDangling else
There is a good reason we always use There is a good reason we always use curly braces in our programscurly braces in our programs
Very common error can be made:Very common error can be made:if (testScore >=60)if (testScore >=60)
if(testScore <= 80)if(testScore <= 80)
System.out.println(“You are in safe range”);System.out.println(“You are in safe range”);
elseelse // Pitfall!// Pitfall!
System.out.println(“You may be in trouble”);System.out.println(“You may be in trouble”);
Boolean OperatorsBoolean Operators
What if we want one expression to What if we want one expression to test multiple conditionstest multiple conditions
Ex. Do they have a score above 50 Ex. Do they have a score above 50 and below 75?and below 75?
Need Need boolean operatorsboolean operators
Boolean operatorsBoolean operators
Can use a logical operator to test Can use a logical operator to test simultaneouslysimultaneously
&&&& ANDAND true if both are true, false true if both are true, false otherwiseotherwise
|||| OROR true if either is true, false true if either is true, false otherwiseotherwise
!! NOTNOT true of the expression is false,true of the expression is false,
false if it is truefalse if it is true
Truth tableTruth table
ExampleExampleif (testScore > 50 && testScore < 75){if (testScore > 50 && testScore < 75){
System.out.print(“In range C to D range”);System.out.print(“In range C to D range”);
}}
ExampleExamplechar c;char c;
……
if (!(c == ‘!’){if (!(c == ‘!’){
System.out.print(c);System.out.print(c);
}}
Many ways to write one expression:Many ways to write one expression:
if (age < 0){if (age < 0){System.out.print(“valid”);System.out.print(“valid”);
} else {} else {System.out.print(“invalid”);System.out.print(“invalid”);
}}--------------------------------------------------------------------------if (!(age >= 0)){if (!(age >= 0)){
System.out.print(“valid”);System.out.print(“valid”);} else {} else {
System.out.print(“invalid”);System.out.print(“invalid”);}}--------------------------------------------------------------------if (age >= 0){if (age >= 0){
System.out.print(“invalid”);System.out.print(“invalid”);} else {} else {
System.out.print(“valid”);System.out.print(“valid”);}}
Precedence TablePrecedence Table
PrecedencPrecedencee
GroupGroup OperatorOperator AssociativitAssociativityy
99 subexpressiosubexpressionn
( )( ) inner to inner to outerouter
left to rightleft to right
88 unaryunary ! -! - right to leftright to left
77 multiplicativemultiplicative * / %* / % left to rightleft to right
66 additiveadditive + -+ - left to rightleft to right
55 relationalrelational < <= > >=< <= > >= left to rightleft to right
44 equalityequality == !=== != left to rightleft to right
33 ANDAND &&&& left to rightleft to right
22 OROR |||| left to rightleft to right
11 assignmentassignment == right to leftright to left
Lazy EvaluationLazy Evaluation Like before, operations evaluated left to Like before, operations evaluated left to
rightright If one part will make the whole expression If one part will make the whole expression
false, quit earlyfalse, quit early
Ex. y = 0;Ex. y = 0;x / y > z && y != 0x / y > z && y != 0 //Run time error, divide by //Run time error, divide by
// zero// zero
y != 0 && x / y > zy != 0 && x / y > z //Legal//Legal
Also called short-circuit evaluationAlso called short-circuit evaluation
Common UsesCommon Uses
Check validity of dataCheck validity of data Divide by zero, out or range errorsDivide by zero, out or range errors
Classify dataClassify data Test above mean, below meanTest above mean, below mean
FlagsFlags Store system settings or user Store system settings or user
preferencespreferences Long messages, noise off, debug modeLong messages, noise off, debug mode
StyleStyle
Equivalent statements give a Equivalent statements give a boolean isRainingboolean isRainingif (isRaining == true){}if (isRaining == true){}
if (isRaining){}if (isRaining){} //Preferred//Preferred
Use good identifier namesUse good identifier names isMoving vs. motionStatusisMoving vs. motionStatus isCheckedOut vs. bookStatusisCheckedOut vs. bookStatus
MOST COMMON ERROR!MOST COMMON ERROR! if (x = 5){}if (x = 5){}
6.2.3 Comparing Strings6.2.3 Comparing Strings
Boolean operators can be used on Boolean operators can be used on objects, but do they mean the same objects, but do they mean the same thing?thing?
To test two Strings, use equals() To test two Strings, use equals() methodmethod
String equalityString equality
Don't use == for strings!Don't use == for strings!if (input == "Y") // WRONG!!!if (input == "Y") // WRONG!!!
Use equals method:Use equals method:if (input.equals("Y"))if (input.equals("Y"))
string1.equals(string2);string1.equals(string2);
== tests identity, equals tests equal == tests identity, equals tests equal contentscontents
equalsIgnoreCase()equalsIgnoreCase()
Case insensitive test ("Y" or "y")Case insensitive test ("Y" or "y")if (input.equalsIgnoreCase("Y"))if (input.equalsIgnoreCase("Y"))
string1.equalsIgnoreCase(string2) // returns string1.equalsIgnoreCase(string2) // returns booleanboolean
compareTo returns which string comes compareTo returns which string comes before the other in the dictionarybefore the other in the dictionary Returns an integerReturns an integer
compareTo()compareTo()
string1.compareTo(string2)string1.compareTo(string2) Returns < 0 if string1 comes firstReturns < 0 if string1 comes first Returns 0 if they are equalReturns 0 if they are equal Returns > 0 if string 2 comes firstReturns > 0 if string 2 comes first
"car"comes before "cargo" "car"comes before "cargo" All uppercase letters come before All uppercase letters come before
lowercase: lowercase: "Hello" comes before "car" "Hello" comes before "car"
6.2.4 Comparing Objects6.2.4 Comparing Objects == tests for identity, equals for identical content == tests for identity, equals for identical content Most classes have an equals() method definedMost classes have an equals() method definedRectangle box1 = new Rectangle(5, 10, 20, 30);Rectangle box1 = new Rectangle(5, 10, 20, 30);Rectangle box2 = box1;Rectangle box2 = box1;Rectangle box3 = new Rectangle(5, 10, 20, 30);Rectangle box3 = new Rectangle(5, 10, 20, 30);
box1 != box3box1 != box3
but box1.equals(box3) but box1.equals(box3)
box1 == box2box1 == box2
Caveat: equals must be defined for the class Caveat: equals must be defined for the class
6.2.4 Testing for null6.2.4 Testing for null
Reference variables store a Reference variables store a reference (address) for an actual reference (address) for an actual objectobject What do they store when they haven’t What do they store when they haven’t
been set to refer to an object?been set to refer to an object?
nullnull is a Java reserved word to is a Java reserved word to designate no object setdesignate no object set
Can be used in tests:Can be used in tests:if (middleInitial == null)if (middleInitial == null)
System.out.println(firstName + " " + lastName);System.out.println(firstName + " " + lastName);
elseelseSystem.out.println(firstName + " " + System.out.println(firstName + " " +
middleInitial + ". " + lastName);middleInitial + ". " + lastName);
Use ==, not equals, to test for null Use ==, not equals, to test for null null is not the same as the empty string null is not the same as the empty string
"" ""
Draw the Memory Draw the Memory DiagramDiagram
String s1 = "Robby", s2;String s1 = "Robby", s2;
s2 = s1;s2 = s1;
:String
R
s1
o b b y
0 1 2 3 4
s2
EqualityEquality
What is the result of:What is the result of: s1 == s2s1 == s2
:String
R
s1
o b b y
0 1 2 3 4
s2
==
because the variables store the same address
trueWhy?
Draw the Memory Draw the Memory DiagramDiagram
String s1 = "Robby", s2;String s1 = "Robby", s2;
s2 = "Robby";s2 = "Robby";
:String
R
s1
o b b y
0 1 2 3 4
s2
EqualityEquality
What is the result of:What is the result of: str1 == str2str1 == str2
:String
R
str1
o b b y
0 1 2 3 4
str2
==
because the variables store the same address
trueWhy?
Draw the Memory Draw the Memory DiagramDiagram
String s1 = "Robby", s2;String s1 = "Robby", s2;
s2 = new String( s1 );s2 = new String( s1 );
:String
R
s1
o b b y
0 1 2 3 4
s2
:String
R o b b y
0 1 2 3 4
EqualityEquality
What is the result of:What is the result of: s1 == s2s1 == s2
:String
R
s1
o b b y
0 1 2 3 4
:String
R
s2
o b b y
0 1 2 3 4
falseWhy?
EqualityEquality
What is the result of:What is the result of: s1 == s2s1 == s2
:String
R
s1
o b b y
0 1 2 3 4
:String
R
s2
o b b y
0 1 2 3 4
==
because the variables store different addresses
EqualityEquality
How do you compare the contents?How do you compare the contents?
:String
R
s1
o b b y
0 1 2 3 4
:String
R
s2
o b b y
0 1 2 3 4
trueWhy?
s1.equals( s2 )
EqualityEquality
How do you compare the contents?How do you compare the contents? s1.equals( s2 )s1.equals( s2 )
:String
R
s1
o b b y
0 1 2 3 4
:String
R
s2
o b b y
0 1 2 3 4.equals( )
because now the contents are compared by the equals method
String String Draw a memory diagram for:Draw a memory diagram for:
String s1 = "Jimmy";String s1 = "Jimmy";String s2;String s2;s2 = s1;s2 = s1;s1 = "Bobby";s1 = "Bobby";
:String
J
s1
i m m y
0 1 2 3 4
?
s2
:String
B o b b y
0 1 2 3 4
String Concatenation String Concatenation The The ++ operator operator Draw a memory diagram for:Draw a memory diagram for:
String s1 = "Jimmy";String s1 = "Jimmy";s1 = s1 + "Bobby";s1 = s1 + "Bobby";
:String
J
s1
i m m y
0 1 2 3 4:String
B o b b y
0 1 2 3 4 5 6 7 8 9
J i m m y
6.4 Using Boolean 6.4 Using Boolean ExpressionsExpressions
6.4.1 introduces boolean data type6.4.1 introduces boolean data type Pioneered by George BoolePioneered by George Boole
double temp = 100;double temp = 100;
System.out.println(“Is it hot?: ” + (temp > 60));System.out.println(“Is it hot?: ” + (temp > 60));
6.4.2 Predicate methods6.4.2 Predicate methods
A predicate method returns a A predicate method returns a boolean valueboolean valuepublic boolean isOverdrawn()public boolean isOverdrawn(){{ return balance < 0; return balance < 0;
}} Use to test conditions – just like Use to test conditions – just like
another other methodanother other method
if (harrysChecking.isOverdrawn()) . . . if (harrysChecking.isOverdrawn()) . . .
Predicate MethodsPredicate Methods
Many predicate methodsMany predicate methods String class: String class: equals() equals()
Character class: Character class: isUpperCase(), isDigit(), isUpperCase(), isDigit(), isLetter(), isLetter(), isLowerCase() isLetter(), isLetter(), isLowerCase()
All public static methodsAll public static methods
Convention is to put prefix “Convention is to put prefix “isis” or ” or ““hashas”” Much like accessors use “Much like accessors use “getget” and ” and
mutators use “mutators use “setset””
ExampleExample
Scanner class has a Scanner class has a hasNextInt() hasNextInt()
method which allows you to test if method which allows you to test if there is an int before you get it (and there is an int before you get it (and cause program to crash)cause program to crash)
Scanner in = new Scanner(System.in)Scanner in = new Scanner(System.in)
int score;int score;
System.out.println(“Enter Score”);System.out.println(“Enter Score”);
if(in.hasNextInt()) if(in.hasNextInt())
score = in.nextInt()score = in.nextInt()
WeightWeight
Say we had a weight class with one int Say we had a weight class with one int parameter “gram” that stores weight in parameter “gram” that stores weight in grams.grams.
What if we really wanted to compare the What if we really wanted to compare the amount of grams each Weight object held?amount of grams each Weight object held?
if (wgt1.getGram() == wgt2.getGram()){if (wgt1.getGram() == wgt2.getGram()){
....
}}
Better SolutionBetter Solution
Create methods in our class to Create methods in our class to handle this problemhandle this problem
String method uses equals( ) method String method uses equals( ) method to compare two stringsto compare two strings
public class Weight{public class Weight{
private int gram;private int gram;
…………..
public boolean equals(Weight public boolean equals(Weight wgtwgt) {) {
boolean boolean resultresult;;
if (this.gram == if (this.gram == wgtwgt.gram){.gram){ result = true;result = true;
} else {} else { result = false;result = false;
}} return return resultresult;;
}}......}}
top related