• Post Reply Bookmark Topic Watch Topic
  • New Topic

about ==  RSS feed

 
krussi rong
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Give following class:
class{
private long val;
public AClass(long v){val=v;}
public static void main(String args[]){
AClass x=new AClass(10L);
AClass y=new AClass(10L);
AClass z=y;
long a=10L;
int b=10;
}
}
which expression result is true?
A.a==b;
B.a==x;
C.y==z;
D.x==y;
E.a==10.0;
the correct answer are: ACE
I counldn't understand AE are correct.
why?
thanks
Krussi
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the JLS, §15.21.1 Numerical Equality Operators == and !=:

If the operands of an equality operator are both of primitive numeric type, binary numeric promotion is performed on the operands (�5.6.2). If the promoted type of the operands is int or long, then an integer equality test is performed; if the promoted type is float or double, then a floating-point equality test is performed.

So, to sum up, a promotion is performed to make the two operands the same data type and then the equality operator is evaluated. That's why A & E are correct.
I hope that helps,
Corey
 
Chintan Rajyaguru
Ranch Hand
Posts: 341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you compare the two values of primitive type (int, long, double, float etc) and if they are of different type, the smaller one is promoted to the biger one and then the comparison is done. In case of choice A variable b is promoted to long (and becomes 10L) and then comparison is done which obviously returns true. Similarly in case of E, variable a is promoted to double.
This is also why you can compare two primitives of different types
if (10.0>9)
{
//something
}
Hope this helps
Chintan
 
Francisco A Guimaraes
Ranch Hand
Posts: 182
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know it�s only a detail, but the class declaration is missing its name, it should be "class AClass {" and not "class {".
Francisco
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!