• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

one question about casting

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
sorry, type long to float is implicit windening conversion,even length of long is 64 and float is 32.
 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!!
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic