• 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

java literals

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hello, i have a question about literals and casting.

I understand why the the next line does not compile:

float f = 3.2;

It is because the decimal numbers in java are double. But the question is: why the next lines compile?

float f = 4/3;
short s = 4/3;

Why the first line does not need "F"?, why the second line does not need (short)?

Thnx
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Jaime Bocanegra:
hello, i have a question about literals and casting.

I understand why the the next line does not compile:

float f = 3.2;

It is because the decimal numbers in java are double. But the question is: why the next lines compile?

float f = 4/3;
short s = 4/3;

Why the first line does not need "F"?, why the second line does not need (short)?

Thnx



4 and 3 are both int literals so the value of 4/3 = 1 can be computed at compile-time.

The first line is fine because an int can be assigned a float reference without a cast.

The second line is fine because assignment conversion includes narrowing primitive conversions that, in this case, allow the int 1 to be assigned a short reference since the value 1 will fit into a short.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic