Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Promotions?

 
sonir shah
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Options are :
1)Code will fail to compile
2)It will print d
3)It will print c
4)It will print b
5)It will print a
Ans : 5)It will print a
I tried running the program , it prints "a"
I feel that the statement(i=f) is not correct and even c++ is wrong?
Am i right?
A bit confused since I cannot understand how are we getting such an output??
Any suggestions?
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the answer is correct. a char primitive contains a numeric value, thus comparison and incrementation are valid operations for chars.
 
Tony reedy
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The expressions are correct.
When "if (i == f) c++;" is evaluated ,i is converted to float and so 5.0 . As 5.0 != 5.5 ,C++ is not evaluated
when"if (((int) (f + d)) == ((int) f + (int) d)) c += 2;"
f+d is added to get a double value 9.3 which is casted to int and result is 9 .
(int)f =5 + (int)d= 3 and the result will be 8.
9!= 8 so rest of the expression is not evaluated
so the answer is 'a'.
hope this explains.
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a good discussion of assignment of literals that's also useful to understand:
http://www.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=014061
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic