Software Engineering I SENG201
Lecture 7 – Decisions and equality in Java March 7, 2022
Copyright By PowCoder代写 加微信 powcoder
Poll on Learn
Lecture pace:
Poll closes 13 March at 1:00pm
Previous lecture
1. Constructors
2. Static variables and methods
3. From one class to multiple classes
4. Encapsulation and visibility
1. Content of objects
2. Decisions in Java
3. Testing for equality
4. Multi-way selection in Java with switch
1. Content of objects
2. Decisions in Java
3. Testing for equality
4. Multi-way selection in Java with switch
A closer look at println()
System.out.println(
Class Property Method
• In class System
• Type:PrintStream
• In class PrintStream • Overloaded
How do we know what System, out, println are?
Class System in API
(Parts of) class PrintStream in API
println() and print()
• For basic (primitive) data types we would not care
• However, what about this?
• How does println() work?
– Creates a string representation of what is passed into println()
System.out.println(5); System.out.println(“Nicole”);
Person myPerson = new Person(“Mona”, 6347, 8); System.out.println(myPerson);
Printing objects – version 1
public class Person {
private int phone; private int shoeSize; private String name;
public Person (String who, int tel, int size) {
name = who; phone = tel; shoeSize = size;
public static void main (String[] args) {
Person myPerson = new Person (“Mona”, 6347, 8); System.out.println(myPerson);
Change string representation of an object (1)
• All classes in Java are “subclasses” of a class Object
• All classes (including our own) can use methods of class Object 11
Class Object in API
Change string representation of an object (2)
• toString() provides string representation of data
• Good practice to write customize toString() in all classes
– Override generic toString() from class Object • How about println()?
– Prints what is returned by public toString() available for all classes
• If not overridden: default string, e.g., object identifier
• If overridden: meaningful string
• String representation not only useful for println()
– Used to store or sending data of objects, show data on user interface, etc.
Printing objects – version 2
public class Person {
private int phone; private int shoeSize; private String name;
public Person (String who, int tel, int size) {
name = who; phone = tel; shoeSize = size;
// override toString() so that it gives useful information about object
public static void main (String[] args) {
Person myPerson = new Person (“Mona”, 6347, 8); System.out.println(myPerson);
[Person: Mona’s phone number is 6347
and shoe size is 8]
public String toString() {
String s = “[Person: ” + name + “’s phone number is ” + phone; s = s + “\n and shoe size is ” + shoeSize + “]”;
1. Content of objects
2. Decisions in Java
3. Testing for equality
4. Multi-way selection in Java with switch
Selection with if: something or nothing
if(Boolean-valued expression) {
Statement(s);
• Java’s if statement has several variations
if (mark >= passMark) System.out.println(“Well done”);
if (myTurn) {
makeMove();
recordScore();
if (Math.abs(x) <= limit) nextIteration(x);
Selection with if-else: either-or decisions
if(Boolean-valued expression) {
Statement(s);
else if(Boolean-valued expression)
Statement(s);
Statement(s);
• Optional else part used for either-or decisions
if (myBet == winningBet) {
addToWinnings(1000);
addToLosses(1000);
Making decisions
• Based on comparison of values (data items or expressions) – Result of comparison using operators is Boolean: true, false
Description
Less than, less than or equal to
Greater than, greater than or equal to
Not equal to
– Relationaloperatorslowerprioritythanarithmeticoperators
• More complex Boolean expressions involve Boolean operators*
– NOT: ! (value is opposite of operand value)
– AND: && (value of (A && B) is true iff the values of A and B are both true)
– OR: || (value of (A || B) is true iff the values of A and / or B are true)
* Ordered based on operator precedence
Some details (practice in your own time)
• Relational operators lower priority than arithmetic operators – Parentheses: often necessary, usually worth consideration
Fast slide
if (i + j > i * 3)… // calculates first, then compares if(!(choice == ‘Q’) && isValid)…
• Multiple comparisons
if (minValue < value < maxValue)... // wrong if ( (minValue < value) && (value < maxValue) )... // right
1. Content of objects
2. Decisions in Java
3. Testing for equality
4. Multi-way selection in Java with switch
Testing for equality
Description
Less than or equal to
Greater than
Greater than or equal to
Not equal to
What happens when we use “==“ with objects? “same” and “identical” are different
Testing for equality – “same”
• Equal object references identify the same object Matthias’ office
Erskine 314
Lecturer’s office
Properties
Phone = 6347
Size = “small” numberWindows = 1
Testing for equality – “identical”
• Distinct references may identify identical objects – Objectswithsamestate
Matthias’ office
Properties
Phone = 6347 numberWindows = 1
Properties
Phone = 6347 numberWindows = 1
Erskine 314
Properties
Phone = 6347 numberWindows = 1
Lecturer’s office
How can we differentiate “same” and “identical” in Java?
Testing for equality
• All classes, implicitly or explicitly, extend class Object • Object has an equals() method
– Can override public boolean equals(Object obj) if needed
• Haven’t we seen something similar before?
– toString() to return String representation of objects – toString() is method in class Object
• Checks if two, possibly distinct, objects are equal
Public class Thing {
int width, height; Thing(int w, int h)
width = w;
height = h;
public boolean equals(Thing aThing) {
if((width == aThing.width) && (height == aThing.height)) return true;
return false;
Example continued
public static void identityCheck(Thing one, Thing other) {
if(one == other) // check for “same” {
System.out.println("refer to same object");
else if(one.equals(other)) // check for “identical” {
System.out.println("refer to identical objects");
public static void main(String[] argv) {
Thing t1 = new Thing(3, 5); Thing t2 = new Thing(3, 5); Thing t3 = t1; identityCheck(t1, t2); identityCheck(t1, t3);
t1 and t2: distinct references to identical Thing objects
t1 and t3: identical references – identify the same object
Additional comments
• What about <, >, =>, <=?
– Could also define other methods (in addition to equals)
• Not part of class Object
– Examples
• largerThan
• smallerThan
• “!=“with objects would be ! equals (i.e., negated equals)
String revisited
• String literals with identical contents do refer to “same” object
– Reason: a string’s value cannot be changed String t1 = “Jen”;
String t2 = “Jen”;
– t1 and t2 refer the same object
• Explicit constructor: different objects with “identical” values String t1 = new String(“Jen”);
String t2 = new String (“Jen”);
– t1 and t2 refer to different but identical objects
• str1 == str2
– Tests whether str1 and str2 refer to the “same” object
– Does not test whether their contents are “identical” – need equals()
Example (practice in your own time)
Fast slide
public class StringLiteral {
public void checkStr(String s) {
String ls1 = "literal string";
String ls2 = "literal string";
System.out.println("ls1 == ls2? " + (ls1 == ls2)); System.out.println("ls1 equals ls2? " + ls1.equals(ls2)); System.out.println("ls1 == s? " + (ls1 == s)); System.out.println("ls1 equals s? " + ls1.equals(s));
public static void main(String[] args) {
StringLiteral me = new StringLiteral(); String s1 = new String("literal" + " string"); String s2 = new String("literal string"); me.checkStr(s1);
System.out.println("======"); me.checkStr(s2);
ls1 == ls2? true ls1 equals ls2? true ls1 == s? false
ls1 equals s? true ======
ls1 == ls2? true ls1 equals ls2? true ls1 == s? false
ls1 equals s? true
More examples (practice in your own time)
Fast slide
String s1 = new String ("literal string"); String s2 = new String ("literal string"); String s3 = new String ("literal string 3"); String ls1 = "literal string";
String ls2 = "literal string";
String ls3 = "literal string 3";
System.out.println("s1 == s2? " + (s1 == s2)); System.out.println("s1 equals s2 " + s1.equals(s2));
System.out.println("s1 == s3? " + (s1 == s3)); System.out.println("s1 equals s3 " + s1.equals(s3));
System.out.println("ls1 == ls2? " + (ls1 == ls2)); System.out.println("ls1 equals ls2? " + ls1.equals(ls2));
System.out.println("ls1 == ls3? " + (ls1 == ls3)); System.out.println("ls1 equals ls3? " + ls1.equals(ls3));
System.out.println("ls1 == s1? " + (ls1 == s1)); System.out.println("ls1 equals s1? " + ls1.equals(s1));
s1 == s2? false
s1 equals s2 true
s1 == s3? false
s1 equals s3 false ls1 == ls2? true
ls1 equals ls2? true ls1 == ls3? false ls1 equals ls3? false ls1 == s1? false
ls1 equals s1? true
1. Content of objects
2. Decisions in Java
3. Testing for equality
4. Multi-way selection in Java with switch
Selecting this, or that
int hunger, thirst;
if(hunger == 1) // not hungry
System.out.println(“I don’t want to eat.”);
else if(hunger == 2) // hungry {
System.out.println(“ have a sandwich?”);
else if(hunger == 3) // very hungry {
System.out.println(“Give me this pizza, now!”);
else if(thirst == 1) // thirsty {
System.out.println(“I am thirsty.”);
else if(hunger == 3 && thirsty == 1) // thirsty and very hungry {
System.out.println(“I am thirsty.”); System.out.println(“Give me this pizza, now!”);
Alternatives disjoint
Complex expressions arise
switch – flow Expression
Expression
Expression
Statement(s)
Statement(s)
Statement(s)
Default statement
switch – format
switch(expression) {
case label1: statement(s); break; case label2: statement(s); break; ...
case labelN: statement(s); break; default: statement(s); break;
– Selects action based on value of expression
– Ordinal / integral type, e.g., int, byte, short or String
– Labels are constant expressions, must be distinct
• default (optional)
public void primeExample(int i) {
switch(i) {
case 3: System.out.print(i);
System.out.println(“ is small prime");
break; case 4:
case 8: System.out.print(i);
System.out.println(“ isn’t prime.”);
default: System.out.print(i);
System.out.println(“ isn’t handled specially.”);
5 isn’t handled specially.
2 is a small prime.
4 isn’t prime.
• switch can have a number of possible execution paths – break and order of labels determine path
– Unlike if-else no need to code each path in a condition
• Deciding on if-else versus switch is based on – Readability
– Expression that the statement is testing
• if-else: based on ranges of values or conditions • switch: based only on single integer*, String
*int, byte, short, char
Another example (practice in your own time)
Fast slide
* Return a printable string for coin name given a value in cents
public static String denominationName(int value) {
String name = “Unknown”;
switch(value) {
What happens for
• value = 10, value = 55 • value = 250, etc.
case 200: name = “twodollar”; break; case 100: name = “onedollar”; break; case 50: name = “fiftycents”; break; case 20: name = “twentycents”; break; case 10: name = “tencents”; break; case 5: name = “fivecents”; break; default:
System.out.println(“No ” + value + “c coin exists”); return name;
1. Content of objects
2. Decisions in Java
3. Testing for equality
4. Multi-way selection in Java with switch
Cartoon of the day
Key lesson: Conditions allow our program to “reason” – this requires differentiating “same” and “identical” when comparing objects.
https://www.cuemath.com/data/conditional-statement/
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com