Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

one question about casting

 
yub huang
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Q: In the following code, what are the legal type
types for the variable vari, which is declared on line 2?
1. class C {
2. public ??? vari;
3. public static void main(String[] args) {
4. foo(vari);
5. }
6. static void foo(float f){
7. System.out.println("f=" + f);
8. }
9. }
a) boolean
b) byte
c) char
d) double
e) float
f) int
g) long
h) short
I think the answers are b,c,e,f,h. but the correct answers are b,c,e,f,g,h. I compile the g
answer, it is really ok, I don't know why. Can someone help me?
 
Bin Wang
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in g, type long to float is implicit windening conversion,even they have same length. so it is correct.
 
Bin Wang
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry, type long to float is implicit windening conversion,even length of long is 64 and float is 32.
 
yuelan
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The conversion is legal because the 32 bits for a float number are divided into two fields: one for magnititude, one for precision and thus the range of a float number is definitely wider than a long number. But note the conversion may result in the loss of accuracy for some large long number.
 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"bill wang1965", "yub" and "yuelan"
Welcome to the JavaRanch! Please adjust your respective displayed names to meet the JavaRanch Naming Policy.
You can change it here.
Thanks, and again welcome to the JavaRanch!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic