• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

simple Java question

Bluga

Banned
Given:

Integer i = new Integer (42);
Long 1 = new Long (42);
Double d = new Double (42.0);
Which two expressions evaluate to True? (Choose Two)
A. (i ==1)
B. (i == d)
C. (d == 1)
D. (i.equals (d))
E. (d.equals (i))
F. (i.equals (42))

Answer: D, E??

can anyone explanis this? Thanks!
 
Ok, here goes:

The first 3 (A,B, and C) most definitely aren't correct.

Object x == Object y iff x IS y! (can't think of any exceptions to this). It doesn't matter if x has the same "value" as y.

Note that for primitive types (int, long, double, etc.) int i = 10, long j = 10 and i==j is true.

F is an illegal statement since .equals() receives an object, and 42 is a primitive type.

D and E are correct!

Use .equals() whenever you want to compare between the values of two objects!

Note, that there are some cases where .equals() is the same as ==, and you might want to override .equals() (or look for alternative methods). For example if you have an array int a[], and another array (remember, arrays ARE objects) int b[], which are of the same length and have the same contents, a.equals(b) will still return false since a and b aren't the same object. In general, this is true of container classes (objects which you use to store other objects). For arrays there exists java.util.Arrays which provides methods to compare equality between two arrays, to sort them, and more.
 
m0ti did a great job of explaining things. 🙂 There's just one thing I thought I'd point out in the example you posted:

Originally posted by: Bluga

Long 1 = new Long (42);

I think you meant to type in "Long l" and not "Long 1". Variables names can't be a number (or start with a number for that matter).
 
Back
Top