Win a copy of Rust Web Development this week in the Other Languages forum!
  • 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:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

Casting hierarchy

 
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm not sure if my wording is exactly correct, so correct me if it's wrong....
It seems casting is necessary when initializing anything below a selected type on the list:
double
float
long
int
short/char
char/short
byte

Example:
double d = 9;
float f = (float)d; //Cast necessary
Question:
1) Example:

Why is casting necessary between float and long even though float is 32 bits and long is 64 bits? Long is bigger, there should be plenty of room.
2)Example:

I believe that short can hold an negative value, and char can't. So, a char can hold more than a short? and a cast is necessary. Why is a cast necessary both ways if one is bigger than the other?
3)Example:

Why is casting necessary both ways if char is 16 bits, and byte is 8 bits?
4)O'yea, by the way, thanks for you help!!!
 
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In JLS 5 all of this is explained.
Any assignment between char and short/byte is regarded as a narrowing conversion, and thus it needs a cast... Except the cases explained in JLS 5.2
 
Willie Toma
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What is JLS? Java L... S...
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
JLS,
Java Language Specification.
Get it here:
http://java.sun.com/docs/books/jls/index.html
You can download it in html, or pdf format (about 4.5 megs).
 
a wee bit from the empire
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic