• Post Reply Bookmark Topic Watch Topic
  • New Topic

java literals  RSS feed

 
Jaime Bocanegra
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • 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
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!