Comparing Objects
Introduction: 3.7.0
- Comparing objects is different than comparing primitive types
- Objects can have many attribute values
- use a special
equals
method to compare all values of an object
String Equality: 3.7.1
equals
compares strings letter by letter- to evaluate
true
, both strings must have the same characters in the same order
- to evaluate
- With objects, you almost always have to use
equals
instead of==
- When
==
is used with objects, it returns true when variables refer to the same object- This is because the variables are
object references
- This is because the variables are
- When
Equality with New Strings: 3.7.2
- If you use
new
when creating a string, it will always create a new string object- Even if the values of two strings are the same, they will not refer to the same object
- Strings created using literals are different
- If a literal of the same value already exists, it is reused
- not on the exam
Comparing with null: 3.7.3
- It is common place to use
==
or!=
to see if an object is null- Can use short-circuit evaluation to avoid an error if the object doesn’t exist
- why would you do this to circumvent an exception instead of using try/catch? This seems like bad practice in languages with Exceptions
- Can use short-circuit evaluation to avoid an error if the object doesn’t exist
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
This was adapted from the CS Awesome curriculum, which was created by
Barbara Ericson, Beryl Hoffman, and many other CS Awesome contributors. All rights reserved.
CS Awesome is licensed under CC BY-NC-SA 4.0.