Equality Flashcards
What does == mean?
It compares primitives and compares if two references point to the same object.
It should not be used to compare Strings but it is legal. Be careful. Pay attention to objects in string pool vs separate objects.
String x = “Hello World”;
String y = “Hello World”;
System.out.println(x == y); // true because they are in pool
What does .equals() do and when can it be used?
equals() is logical equality IN STRINGS and ARRAY LISTS. It compares the values inside two Strings. For other objects it compares reference equality just like ==. The method can be used to compare any two objects of the same type only String compares inside.
What does == do with two Strings?
Calling == on String objects will check whether they point to the same object in the
pool.
What does == do with two StringBuilder references?
Calling == on StringBuilder references will check whether they are pointing to the same StringBuilder object.
What does .equals() do with two Strings?
Calling equals() on String objects will check whether the sequence of characters is the same.
What does .equals() do with two StringBuilder references?
Calling equals() on StringBuilder objects will check whether they are pointing to the same object rather than looking at the values inside.
What is this result?
short s =9;
Integer k = 9;
System.out.print(s==k);
True. Autounboxing occurs then the primitive values are compared. One will be promoted if necessary.
Is this valid?
System.out.println(Double.parseDouble(“3.0”).equals(Integer.parseInt(“3”)));
No, when the operations are performed they produce primitives. The .equals method cannot be used on primitives. This will not compile.
What's the difference? if (b2 = !b1 = b2){ if (b2 = !b1){ if (b2 != b1 = b2){ //if (b2 = b1 != b2){
if (b2 = !b1 = b2){//does not compile because of !b1=b2.
!b1 is not a variable that can receive an assignment. It’s a value.
if (b2 = !b1){ // Ok, just assignment and it evaulates to a boolean
if (b2 != b1 = b2){ // compiler error because the first two create a boolean result then it tries to assign a value tp that result.
//if (b2 = b1 != b2){ //ok, assignment then comparison
Is this valid? System.out.println(new Double(3.0).equals(new Double(3.0)));
Yes because this is comparing two objects. It does not result in the comparison of primitives.
Is this legal?
static int num = 1;
static int num2 = 1;
System.out.println(num.equals(num2));
No, can’t do .equals() on primitives
What is the result? System.out.println(new Double(3.0).equals(new Float(3.0)));
False. .equals looks at object type and inside
What is the result? System.out.println(new Double(3.0).equals(new Double(3.0)));
True .equals looks looks at object type and inside